-
Notifications
You must be signed in to change notification settings - Fork 50.3k
Closed
Description
Do you want to request a feature or report a bug? bug
What is the current behavior?
The following piece of code breaks the rules of hooks:
import {useState} from 'react';
const MyComponent = () => {
const [foo, setFoo] = useState ();
if ( !foo ) return;
const [bar, setBar] = useState ();
return null;
};The lint rule reports:
React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
What is the expected behavior?
My understanding is that for hooks to work they need to be called always in the same order, otherwise returned values can't be properly mapped to function calls.
In my piece of code the hooks are always called in the same order, but some times we exit early, which is slightly beneficial both for performance and for writing clean code.
Shouldn't this just work?
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? v16.8.6
OmriAroesti, EleRam, AdrianDiazG, nratter, benoitkoenig and 7 more
Metadata
Metadata
Assignees
Labels
No labels