Skip to content
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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

patorjk
Copy link

@patorjk patorjk commented May 17, 2023

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

@legendkong
Copy link

+1 🤪

],
},
{
code: 'useState(a() && b())',

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) {

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

Suggested change
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;
}
},
};
},

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[eslint-plugin-react-hooks] New rule to enforce lazy initialization for useState
4 participants