Apr 13 2024
Hooks are a feature introduced in React 16.8 that allow you to use state and other React features without writing a class component. However, there are certain rules that you need to follow when using hooks. One of these rules is that you cannot use hooks inside an if
statement.
The reason why you cannot use hooks inside an if
statement is that hooks rely on the order in which they are called (the hook call chain). When you use a hook, React keeps track of the order in which the hooks are called and uses that information to manage the state and other resources associated with that hook.
Let’s take a look at an example of a simple functional component:
function Component() {
const [title, setTitle] = useState('Title');
const [description, setDescription] = useState('Description');
function logTitle() {
console.log(title);
}
function logDescription() {
console.log(description);
}
useEffect(logTitle);
useEffect(logDescription);
}
In this example, the hooks are called in the following order on every render:
useState('Title')
useState('Description')
useEffect(logTitle)
useEffect(logDescription)
React needs to call these hooks in that order every time. If you were to put one of the useState
calls inside an if
statement, it would break the chain order and could lead to bugs.
That’s all. I hope you enjoyed this article. If you have any questions, feel free to ask them in the comments.
Here’s an addon for you. Brief summary of an article. You can use it to create fiches cards (e.g. in Anki).
The hook call chain refers to the order in which hooks are called within a functional component.
The hook call chain is important because hooks must be called in the same order on every render of a functional component. This is because hooks rely on the order in which they are called to maintain their internal state, performance and behavior.