-
Notifications
You must be signed in to change notification settings - Fork 49.4k
[eslint-plugin-react-hooks] Report constant constructions #19590
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
The dependency array passed to a React hook can be thought of as a list of cache keys. On each render, if any dependency is not `===` its previous value, the hook will be rerun. Constructing a new object/array/function/etc directly within your render function means that the value will be referentially unique on each render. If you then use that value as a hook dependency, that hook will get a "cache miss" on every render, making the dependency array useless. This can be especially dangerous since it can cascade. If a hook such as `useMemo` is rerun on each render, not only are we bypassing the option to avoid potentially expensive work, but the value _returned_ by `useMemo` may end up being referentially unique on each render causing other downstream hooks or memoized components to become deoptimized.
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. Latest deployment of this branch, based on commit 31f75cd:
|
getConstructionExpresionType(node.left) != null || | ||
getConstructionExpresionType(node.right) != null | ||
) { | ||
return 'logical expression'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For even better developer experience, we could try to blame the actual sub-expression that is a construction.
For example:
const foo = bar ?? [];
^^ This is actually to blame
However, it would add some additional complexity.
FYI @gaearon who suggested we add this here rather than as a separate rule. cc @dylanOshima who paired with me on the original, standalone, version of this rule. |
Details of bundled changes.Comparing: c8d9b88...31f75cd eslint-plugin-react-hooks
Size changes (stable) |
Details of bundled changes.Comparing: c8d9b88...31f75cd eslint-plugin-react-hooks
Size changes (experimental) |
The |
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Show resolved
Hide resolved
I got this working on VSCode with some actual production code and looked at a few examples. Some thoughts: Suggestions are helpful but clunkyIf I have a conditional array construction in my render function the flow looks like this:
Overall this is clunky, but at least I get an error at each point and the error tells me what to do. Should our suggested fix include an empty dependency array? That changes the semantics, but gets the user closer to a fix, assuming they listen to other lint advice. Wrapping only the declaration may cause bugs if the value gets mutatedConsider this case:
Currently we offer an automatic suggestion to wrap the declaration in
Maybe we need to check for the case where the value gets mutated and not offer an automated fix in that case |
Can we suggest a filled-in array in the first place? |
Yeah — this is really, really bad. How do you feel about starting without an autofix at all? We can maybe add it later if it's too burdensome. |
Sounds good. Should we leave the autofix for functions on the assumption that it's not very common for folks to mutate functions? |
I'm sure we could, I haven't looked hard enough to know exactly how much work it would be. I saw this comment (maybe you wrote it?) and just assumed it would be more work than was worth it for now.
|
Yeah I think that's reasonable to keep. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's remove the risky useMemo wrapping for new cases
@gaearon Actually, I'm trying to think how hard it would be to detect cases where the value might have been mutated. Would it be sufficient to identify cases where the object has one of its properties read/written/called? If it's that simple, and if the ESLint scope API can give us that info easily (I'm still new to that API and it's poorly documented) then maybe it would be possible to allow the fix in the common case where the value is not mutated. |
One way to tell is to go through |
It may not be safe to just wrap the declaration of an object, since the object may get mutated. Only offer this autofix for functions which are unlikely to get mutated. Also, update the message to clarify that the entire construction of the value should get wrapped.
Updated:
|
I'll punt on trying to detect potential ussages for now. |
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
Gonna review this tomorrow morning. |
) { | ||
suggest = [ | ||
{ | ||
desc: `Wrap the construction of '${construction.name.name}' in its own ${wrapperHook}() Hook.`, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Other options instead of construction
:
instantiation
initialisation
(add a z if you want to americanise it 😉)assignment
const [before, after] = | ||
wrapperHook === 'useMemo' | ||
? [`useMemo(() => { return `, '; })'] | ||
: ['useCallback(', ')']; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit - could pull this up to L857 where you declare wrapperHook
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since this is only used within the actual fix, it seemed reasonable to have it here.
return null; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe that you could also add support for JSX here, because under the hood they are going to create a new object ref each render (right? I don't know the exact semantics of JSX transforms)
const frag = <></>; // JSXFragment
const comp = <div />; // JSXElement
useMemo(() => {}, [frag, comp]);
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could also add handling for AssignmentExpression
:
let x = null;
let y = x = () => {};
useMemo(() => {}, [y]);
(i.e. ignore the node and check the right
)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could also add handling for NewExpression
?
const x = new Map();
useMemo(() => {}, [x]);
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could also add handling for Literal
when value instanceof RegExp
?
const x = /a/;
useMemo(() => {}, [x]);
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could also handle TS type assertions (TSAsExpression
):
const x = {} as any;
useMemo(() => {}, [x]);
(i.e. ignore the node and check the expression
.)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could also handle flow type casts (TypeCastExpression
):
const x = ({}: any);
useMemo(() => {}, [x]);
(i.e. ignore the node and check the expression
.)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This list is gold. Thanks! I had intentionally omitted NewExpression
thinking that String
Number
and Boolean
would be compared by value, but I forgot that they will be boxed so presumably they will be referentially unique and therefore worth flagging.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is such an edge case btw. I don't think handling boxed primitives is super important.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@gaearon I would agree that it's very unlikely to happen, we get it for free when handling other NewExpression
s like new Map([])
.
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
Outdated
Show resolved
Hide resolved
You'll want to add some tests for cases where the same variable is used by multiple |
f4c38b0
to
eaa2aff
Compare
For patterns where an object doesn't use any values from the pure scopes, would it be possible to change the message to suggest to move it outside the component scope? This is a lot less noisy and seems fairly common in practice. |
Good suggestion, but I think it would require significantly more analysis. Currently we don't do any work to try to understand the values used to construct the object. If we did, not only could we adjust the message as you suggest, but we could also construct the dependency array for the autofix of adding a wrapping |
Will it also handle cases like default props? e.g.: function Foo({ arr = [] }) {
useMemo(() => {
console.log(arr);
}, [arr]);
} |
@nstepien Good question. It doesn't currently. It looks like it wouldn't be too hard to add though. Here's a commit that adds it: 29d560b I'm happy to open that as a PR, but I suspect we would want to come up with a somewhat different error message in that case, and I'm not sure I have the time right now to work on that (maybe you do?). Thoughts @gaearon? Do you agree that we would want to different error message for the default param case? |
That would need a different message, yes. |
@captbaritone Checking for default props is still missing, do you think you could work on it? I can log an issue otherwise. function useArr(arr = []) {
useEffect(() => {
console.log(arr);
}, [arr]);
}
// or
function useArr({ arr = []} ) {
useEffect(() => {
console.log(arr);
}, [arr]);
} |
Summary
This PR expands upon the existing logic which will report functions defined inside the render function as invalid hook dependencies.
We can now detect additional types of expressions which will result in values that will be referentially unique on each render, such as
[]
or{}
.We also detect cases where an expression may conditionally result in a referentially unique on each render, such as
someArr ?? []
orsomeObj || {}
.Test Plan
yarn jest