Sub topic 1
The Rules of Hooks You Must Keep
Prerequisites
Assume you know function components, JSX, props, useState, and useEffect. You should also know JavaScript closures and destructuring.
The Rules of Hooks You Must Keep
A Hook is a React function that lets a component use features such as state or effects. React identifies Hook state by the order in which Hooks run. Keep that order unchanged on every render.
Follow these rules:
- Call Hooks only at the top level of a function component or custom Hook.
- Do not call a Hook inside a condition, loop, nested function, or event handler.
- Call Hooks only from React function components or functions whose names start with
use. - Keep the same Hook calls in the same order on every render.
What a Custom Hook Is
A custom Hook is a JavaScript function starting with use that calls other Hooks. It packages reusable stateful behavior without adding a component to the rendered tree.
For example, useToggle hides the state update while exposing a small interface:
import { useCallback, useState } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => {
setOn((value) => !value);
}, []);
return [on, toggle];
}The use prefix is a convention that helps developers and lint tools recognize a custom Hook.
Extracting Duplicated Logic Into a Hook
If two components repeat the same state and event logic, move that logic into a custom Hook. Each component can then choose its own markup:
function Panels() {
const [openA, toggleA] = useToggle();
const [openB, toggleB] = useToggle();
return (
<>
<button onClick={toggleA}>{openA ? 'Hide A' : 'Show A'}</button>
<button onClick={toggleB}>{openB ? 'Hide B' : 'Show B'}</button>
</>
);
}Hooks Share Logic, Not State
Every call to a custom Hook is independent. openA and openB do not share a value because they come from separate useToggle() calls. The Hook shares the state-management recipe, while React stores separate state for each call.
Exercise
Why must a custom Hook call its Hooks at the top level?
Show answer
React relies on a stable call order to match each Hook call with its stored state and effects.