Why Do We Need To Call React Hook at the Top Level? Why Can’t We Call It Inside a Loop or Condition?

February 14, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

In the official React documentation, there is an article specifically discussing the rules for using Hooks, which includes the restriction to "not call Hooks inside loops, conditions, or nested functions" and the requirement to "only call Hooks at the top level". So, why are these rules in place? Let's understand this issue together.

How Does React Know Which State Corresponds to Which useState?

Before discussing the rules for using Hooks, let's take a look at a code snippet with the useState Hook. After reading it, think about how React knows which state corresponds to which useState.

import { useState } from "react";

export default function MyComponent() {
  const [number, setNumber] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextNumber() {
    setNumber(number + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  return (
    <>
      <button onClick={handleNextNumber}>Next</button>
      <h3>{number + 1}</h3>
      <button onClick={handleMoreClick}>
        {showMore ? "Hide" : "Show"} details
      </button>
      {showMore && <p>Hello World!</p>}
    </>
  );
}

The code example above uses two useState Hooks, but we do not pass any identifiable values to useState. So, how does React know which state corresponds to which useState? The answer is that if the order of Hook calls is stable, React can correctly associate the internal state with the corresponding Hook.

As shown in the example, each Hook has the same call order during each component render. As long as the call order remains consistent, React can correctly associate each internal state with the corresponding Hook. However, if a Hook is not called in accordance with React's rules, such as in an if...else statement, the order of renders may change, causing React to lose track of each Hook's corresponding state.

This is why we should not call Hooks within loops, conditional statements, or nested functions, and we should only call Hooks at the top level.

Understanding this basic concept should earn a passing score in a technical interview.

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee