Conditional Hook Issue

Learn about practical applications of conditional hooks and understand scenarios where they might not be the optimal solution.

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 string
const a = flag ? _useHook('a') : ' ';
// Use _useHook('b') unconditionally
const b = _useHook('b');
return <h1>Hello World+{a}{b}</h1>;
}
Conditional usage of custom hook in a function component

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 b ...