From aed8c9b6097aa6d7b77dd766df106a8d351bbbb8 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Fri, 19 Aug 2022 17:51:51 +0100 Subject: [PATCH] [ESLint] Treat useEvent retval as stable --- .../__tests__/ESLintRuleExhaustiveDeps-test.js | 12 ++++++++++++ .../eslint-plugin-react-hooks/src/ExhaustiveDeps.js | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js b/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js index 5c3c64c173fa9..3fd1fd9dff227 100644 --- a/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js +++ b/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js @@ -1452,6 +1452,18 @@ const tests = { } `, }, + { + code: normalizeIndent` + function MyComponent({ theme }) { + const onStuff = useEvent(() => { + showNotification(theme); + }); + useEffect(() => { + onStuff(); + }, []); + } + `, + }, ], invalid: [ { diff --git a/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js b/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js index c2341886872c1..fc388f21a30ef 100644 --- a/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js +++ b/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js @@ -157,6 +157,8 @@ export default { // ^^^ true for this reference // const ref = useRef() // ^^^ true for this reference + // const onStuff = useEvent(() => {}) + // ^^^ true for this reference // False for everything else. function isStableKnownHookValue(resolved) { if (!isArray(resolved.defs)) { @@ -223,6 +225,9 @@ export default { if (name === 'useRef' && id.type === 'Identifier') { // useRef() return value is stable. return true; + } else if (name === 'useEvent' && id.type === 'Identifier') { + // useEvent() return value is stable. + return true; } else if (name === 'useState' || name === 'useReducer') { // Only consider second value in initializing tuple stable. if (