Extracting a Hook

What this is. A function whose name starts with use and which calls other hooks. That is the entire definition.

It is how you take a piece of stateful logic out of a component so another component can use it too.

What is shared and what is not. The logic is shared. The state is not. Each component calling your hook gets its own separate copy, exactly as if it had written the code inline.

People expect the opposite the first time and are surprised when two components do not see each other's values. If they genuinely need to share one value, that is context or lifted state, not a hook.

Try it

Open the first panel. The second stays closed, because each call to useToggle made its own state.

loading editor…

loading React…

✦ The name is not decoration

The rules of hooks can only be checked on functions that look like hooks. A function starting with use is checked; one that does not is not, and calling useState inside it silently breaks the rules. Name it useSomething or do not call hooks in it.

◈ Graded Component

Write a custom hook called useCounter that takes a starting number and returns an object with a value, an increment function, and a reset function. Then use it in App twice: once for a counter shown in an element with id a, incremented by a button with id inca, and once for a counter shown in an element with id b, incremented by a button with id incb. The two must be completely independent.

Checked against what your component renders and how it responds, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: The Rules of Hooks →
← Back