Junior (0-2 years)React

What are React hooks and what are the rules of hooks?

Quick answer

Hooks are functions such as useState and useEffect that let function components use state, lifecycle behaviour and other React features; they must be called at the top level of a component or custom hook, never inside loops, conditions or nested functions.

Before hooks, state and lifecycle methods required class components. Hooks let you do the same in function components and, importantly, let you extract and reuse stateful logic as custom hooks without wrapper components or render props.

React tracks hooks by the order in which they are called during each render. If a hook is skipped in one render because of an if statement, every hook after it would read the wrong state. That is why the two rules exist: only call hooks at the top level, and only call them from React function components or other custom hooks (whose names start with use). The eslint-plugin-react-hooks package enforces both.

function useWindowWidth() {                 // custom hook
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const onResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return width;
}

Key points

  • Call hooks at the top level only
  • Call hooks only from components or custom hooks
  • React relies on call order to match state to hooks

Questions interviewers ask next

  • How do you write a custom hook?
  • What is the difference between useState and useReducer?