Bug: rules-of-hooks should support hooks inside top-level IIFEs
See original GitHub issueReact version: v16.13.1 eslint-plugin-react-hooks version: v3.0.0
Steps To Reproduce
- Write something like this:
const Component = () => {
(() => {
useState ();
})()
};
- Run the
rules-of-hooks
linter rules on it.
The current behavior
Those linter rules will complain that the useState
hook is being called inside a callback.
The expected behavior
Those linter rules should be a little smarter and ignore this kind of top-level IIFE “callback”, since if I’m understanding things correctly it’s completely safe to call hooks this way.
This is a bit of an edge case, but I’m wrapping some hook calls in an IIFE because I don’t want to be able to access the values they return directly, as they may not be the most up to date, rather than via the accessor my IIFE returns.
Issue Analytics
- State:
- Created 3 years ago
- Comments:11 (1 by maintainers)
Top Results From Across the Web
Rules of Hooks - React
Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any...
Read more >Trouble with React Hooks, which react hook rule am I breaking?
Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function.
Read more >Invalid hook call. Hooks can only be called inside the body of ...
React error “Invalid hook call. Hooks can only be called inside the body of a function component” occurs due to many reasons. Learn...
Read more >Understanding common frustrations with React Hooks
React Hooks can be frustrating despite their popularity and widespread use. Learn about some of the drawbacks to using React Hooks.
Read more >Rules of React Hooks - CoderPad
The top level of a functional component is the base of your function body before you return your JSX elements. This is where...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This particular case is a rather exotic pattern and in my opinion isn’t worth adding complexity to the (already complex) rule implementation.
As an alternative with similar scoping “benefits”, you can use a block.
@wereHamster The above example could compose decently with expression chaining…
If you need more complexity in a self-contained block, you could mimic the
do
expression proposal with your named IIFE…I don’t feel like that’s any clunkier than an anonymous IIFE; it’s arguably more self-descriptive.