-
Notifications
You must be signed in to change notification settings - Fork 47.3k
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
ESLint rule for detecting function calls inside useState (for recommending lazy initialization) #26822
ESLint rule for detecting function calls inside useState (for recommending lazy initialization) #26822
Conversation
+1 🤪 |
], | ||
}, | ||
{ | ||
code: 'useState(a() && b())', |
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.
Here you should get two errors. Because you have
two function calls.
}, | ||
}, | ||
|
||
create(context) { |
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 think code will be clearer if you just ban all calls inside useState
create(context) { | |
create: (context) => { | |
let useStateCallExpression = null; | |
return { | |
CallExpression(node) { | |
if (node.callee.type === 'Identifier' && node.callee.name === 'useState') { | |
useStateCallExpression = node; | |
return; | |
} | |
if (useStateCallExpression) { | |
context.report({ node, messageId: 'useLazyInitialization' }); | |
} | |
}, | |
'CallExpression:exit': function (node) { | |
if (node === useStateCallExpression) { | |
useStateCallExpression = null; | |
} | |
}, | |
}; | |
}, |
This pull request has been automatically marked as stale. If this pull request is still relevant, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize reviewing it yet. Your contribution is very much appreciated. |
Thanks for the PR! With React Compiler, we are working on optimizations to ensure that useState initializers only run once, so this will become automatic and not something that developers have to think about. I'll go ahead and close since this is already work-in-progress but via a different approach, but we really appreciate the contribution! |
Summary
Adds a new ESLint rule to detect function calls inside useState and recommends that an initializer function be used instead. For example, this code:
const [value, setValue] = useState(generateTodos());
Would trigger the rule into recommending this instead:
const [value, setValue] = useState(() => generateTodos());
More info: React docs on avoiding recreating initial state
How did you test this change?
I added a test file with various tests. The test file passes when I run "yarn test".
As an aside, initially I submitted this to eslint-plugin-react, but they felt this would be a better place for it.
Closes #26520