liveBook · Manning

Rules of hooks

As explained in React Hooks in Action: With Suspense and Concurrent Mode

The Rules of Hooks are React conventions requiring Hooks to be called only from function components or custom Hooks and only at the top level of those functions.

React Hooks make function components stateful and let them coordinate effects such as data loading or subscriptions. Their flexibility depends on keeping Hook calls consistent across renders. section 9.0 section 9.2

Follow three conventions:

  • Start custom Hook names with use, as in useFetch, useUsers, or useLocalStorage. section 9.2 section 9.1.2
  • Call Hooks only at the top level: never inside conditionals, loops, or nested functions. section 9.6
  • Call Hooks only from React function components or custom Hooks, not from ordinary JavaScript functions. section 9.2 section 9.6

React relies on Hook calls having the same order and number on every render to track state, effects, batched updates, UI differences, and scheduled DOM changes. section 9.2

Condition the effect, not the Hook call

When an effect should run only under certain conditions, keep useEffect at the top level and place the condition inside it:\n\nuseEffect(() => {\n if (condition) {\n // perform task.\n }\n}, [dep1, dep2]); section 9.6

Use eslint-plugin-react-hooks to detect violations. Projects created with create-react-app already include the plugin. Custom Hooks can encapsulate state and effects while returning only the values components need. section 9.2.3 section 9.6

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains naming, placement, call-order rationale, conditional effects, and linting, without detailing React’s internal tracking implementation.
Examples
Uses useDocumentTitle, useFetch, useUsers, useLocalStorage, and a conditional useEffect pattern.
What it assumes
Assumes familiarity with React function components and Hooks while teaching custom Hook naming and placement conventions.
What you can do after
Apply the rules when extracting custom Hooks and use ESLint to detect misplaced or inconsistently called Hooks.
How it connects
Connects custom Hooks with function components, useState, useEffect, state management, side effects, and ESLint.

Also explained in

Compare how 2 books explain rules of hooks →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.