Various errors can be triggered from React when there is either a change in the number of hooks, or the order in which hooks are called changes. React documents these limitations/rules here and also documents ways to fix the various errors.
I understand that these rules exist, but why do they exist? The above page states
React relies on the order in which Hooks are called
but why did the React team decide to rely on what appears to be be an array-like structure rather than a keyed object to access hook calls? There doesn't seem to be any React documentation that details if this even was a design decision or if it's inherent to the way hooks have to work 'under-the-hood'.
CodePudding user response:
I believe the explanation is right here: https://reactjs.org/docs/hooks-rules.html#explanation
From the documentation details :
React relies on the order in which Hooks are called
If we want to run an effect conditionally, we can put that condition inside our Hook
This is so each components maintains its state consistently. It avoids errors like call on undefined hook or effect variable and total component re-render if the state isn't maintained properly.
CodePudding user response:
Since we can use multiple hooks in a single component, React needs a stable way to call them correctly, in the right order. Think about it this way: You start your component with a useState()
, which contains data that will be used across re-renders. What will React do if you remove the hook? Where should the data go? Where should the state go? React is not designed for such use cases.
How it does work, though, is by relying on the order in which Hooks are called. Did you notice that the hooks are just functions, without any sort of order parameters? The way React can know in which order to call them, is by keeping track of in which order you wrote them. Removing a hook would break this order and create inconsistencies and errors.
On the page you have linked, there is an explanation section, which further answers your question with a good example.
CodePudding user response:
Yes, the order is very important.
I can only guess why they choose to do it like this.
You component is just a function actually. The hooks are defined outside of your component (function) so when a hook is called (for instance a useState
) they need a way to identify which hook is being called so they can return the same setState
every time.
They could've added an identifier to the call, but it would've been your responsibility to pass unique identifiers to this call. Even more the id needs to be unique in the entire view tree. This means that you should've define a way to have unique ids in the entire application.
Using the order fixes this problem.