react icon indicating copy to clipboard operation
react copied to clipboard

ESLint rule for detecting function calls inside useState (for recommending lazy initialization)

Open patorjk opened this issue 2 years ago • 1 comments

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 https://github.com/facebook/react/issues/26520

patorjk avatar May 17 '23 02:05 patorjk

+1 🤪

legendkong avatar May 18 '23 09:05 legendkong

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.

github-actions[bot] avatar May 30 '24 19:05 github-actions[bot]

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!

josephsavona avatar May 30 '24 20:05 josephsavona