React Hooks, introduced in React 16.8, revolutionized how state and side effects are handled in function components. However, to ensure their consistent behavior and optimal functionality, there are specific rules that developers need to follow when using them:

  1. Only Call Hooks at the Top Level: Hooks shouldn’t be called inside loops, conditions, or nested functions. This rule ensures that the order of Hook calls remains consistent across multiple renders, allowing React to correctly associate the state and effects with their respective Hooks.


  1. Only Call Hooks from React Functions: Hooks should be called from React function components, not regular JavaScript functions. There’s an exception for custom Hooks, which is essentially a convention where the function name starts with ‘use’, and that function can call other Hooks.


  1. Use the ESLint Plugin: The React team provides an ESLint plugin, `eslint-plugin-react-hooks`, that enforces these two primary rules. It’s highly recommended to use this plugin when developing with Hooks as it helps catch violations of these rules.

The rationale behind these rules lies in how React keeps track of Hooks. React relies on the order in which Hooks are called to determine which state variable corresponds to which useState call, for example. If Hooks were to be called conditionally or inside loops, this order might change between renders, leading to bugs that are challenging to diagnose.

By following the rules of Hooks, developers can harness their power, making code more readable, and reducing the complexities previously associated with class components, lifecycles, and state management, while still ensuring stable and predictable behavior in their applications.

Previously at
Flag Argentina
time icon
Seasoned Software Engineer specializing in React.js development. Over 5 years of experience crafting dynamic web solutions and collaborating with cross-functional teams.