Conditional Hook Issue
Explore the pitfalls of using conditional hooks in React and understand how the runtime order of hooks affects state management. Learn why hooks should always be called unconditionally at the top level of your components. This lesson helps you avoid common mistakes that lead to unpredictable state behavior and warnings, ensuring your React applications run smoothly.
We'll cover the following...
React relies on the order of hooks to serve as keys, eliminating the need for explicit key usage. This means that if hook A is called first and hook B is called second, the order of states is appropriately marked. While this design is convenient, it comes with a caveat: the calling order is determined at runtime, not during code compilation. This runtime variability is a potential concern, but with awareness and careful coding practices, this design remains highly functional. To give an example, we can set up a case using an if statement.
Conditional hook I
Let's say we have the following Title component with two usages of hooks:
const Title = ({ flag }) => {// Use _useHook('a') if the flag is truthy; otherwise, use an empty stringconst a = flag ? _useHook('a') : ' ';// Use _useHook('b') unconditionallyconst b = _useHook('b');return <h1>Hello World+{a}{b}</h1>;}
In this code logic, what we intend to do is store the 'a' and 'b' chars in the a and b variables, respectively. Except, when the flag is false, an empty char ' ' is stored in the a variable.
To confirm whether the code works, let's make two updates to this component while flipping the flag prop. Suppose for the first update that the flag prop is set as true and for the second update, it gets changed to false. For this setup, it generates the following timeline sketch:
|T-------F---------------> flag|a------- ---------------> a|b-------a---------------> b
At the first update, both a and b variables are assigned correctly. But when it comes to the second update, the ...