⚛️ React Q13 / 113

Rules of hooks in React?

AI-Powered Answer ✓ Answered

React Hooks are special functions that let you 'hook into' React features like state and lifecycle methods from functional components. To ensure predictable behavior and avoid subtle bugs, there are two fundamental rules that govern how hooks must be used.

Rule 1: Only Call Hooks at the Top Level

This rule means you should not call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the very top level of your React function component or custom Hook. This ensures that Hooks are called in the same order each time a component renders.

Calling hooks conditionally or inside loops would mean their order could change between renders, which React depends on to correctly associate local state with specific useState and useEffect calls. Violating this rule can lead to bugs that are difficult to debug, as React might return incorrect state or effects.

Rule 2: Only Call Hooks from React Functions

You should only call Hooks from React functional components or from custom Hooks. Do not call Hooks from regular JavaScript functions. This prevents you from using Hooks in arbitrary JavaScript code where their internal state management would not make sense.

This rule ensures that Hooks are always used within the context of a React component's lifecycle, allowing React to properly manage their state and effects. Calling them from non-React functions would decouple them from the React rendering cycle, leading to errors.

Why These Rules?

React relies on the order in which Hooks are called. When you call useState multiple times in a component, React associates each state variable with a specific position in an internal array. If the order of these calls changes between renders, React won't know which state corresponds to which useState call, leading to unexpected behavior and errors. These two rules ensure that the call order remains consistent.

Enforcement with ESLint Plugin

To help developers adhere to these rules, the React team provides an ESLint plugin called eslint-plugin-react-hooks. It includes a rule (react-hooks/rules-of-hooks) that automatically checks for violations of these two fundamental rules during development, providing immediate feedback and preventing common mistakes.