liveBook · Manning

React hook

As explained in React Quickly, Second Edition

React Hooks are functions that let functional components access React features such as state and lifecycle-related behavior.

A React hook is a special function that connects a functional component to React features. For example, `useState` lets a component keep a value between renders. Hooks were introduced in React 16.8; names beginning with `use` identify hooks by convention. section 5.2.1

Keep a UI value

Start with `const [isVisible, setVisible] = useState(false);`. Call `setVisible(true)` to show something and `setVisible(false)` to hide it. Updating state through a stateful hook causes the component to re-render. section 11.5.2 section 6.2

Built-in hooks serve different jobs:

  • Stateful hooks, including `useState`, `useReducer`, and `useContext`, help components work with state. section 7.0
  • Effect hooks such as `useEffect` run side effects during a component’s life cycle. section 7.8
  • Memoization hooks help avoid unnecessary recalculation; advanced library hooks chiefly serve reusable component libraries. section 7.0 section 7.4

Call hooks at the top level of a functional component, in the same order on every render. Do not put a hook in a condition, loop, callback, or class component. A custom hook may call other hooks, but it too must be called from a component or another custom hook. section 7.5 section 5.2.1

function Counter({ isVisible }) {
  const [counter, setCounter] = useState(0);   #1
  if (!isVisible) {
   return null;                                #2
  }
  return (
    ...
  );
}

The counter initializes `useState` before checking whether it should return early. Moving that return above the hook would make the hook call conditional. section 5.2.1

Reuse context access

When several components need the same context, a small custom hook can wrap `useContext`: `function useAPI() { return useContext(APIContext); }`. Components can then call `useAPI()` instead of repeating the context lookup. section 11.5.2

How React Quickly, Second Edition covers it

How deep it goes
Defines hooks, groups their purposes, and works through call-order rules while flagging library hooks as advanced.
Examples
Uses visibility state, an early-return counter, and a custom hook for repeated context access.
What it assumes
Starts with functional components and introduces what makes a hook special before stating its usage rules.
What you can do after
Apply it via React’s useState and useContext, and place hook calls consistently across renders.
How it connects
Connects hooks to functional components, component state, re-rendering, side effects, React Context, memoization, and custom hooks.

Also explained in

Compare how 3 books explain React hook →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.