React Foundations · Composition

Extracting a custom hook

Custom hooks

Extracting a custom hook

When several components share the same stateful logic, copying it into each one gets old fast. Pull it into a custom hook: a function whose name starts with use that calls other hooks and returns what the component needs.

function useCounter(initial) {
  const [count, setCount] = useState(initial);
  const increment = () => setCount((current) => current + 1);
  return { count, increment };
}
function App() {
  const { count, increment } = useCounter(0);
  return <button onClick={increment}>Count: {count}</button>;
}

A custom hook is a function — but because it calls useState (or useEffect, or another hook), React applies the rules of hooks to it. That is why its name must start with use: React uses the name to know it is a hook.

The hook owns the logic; the component owns the rendering. You can reuse useCounter in any component that needs a counter.

A custom hook shares logic, not state. Each call to useCounter gets its own separate state, so two components that call it keep two independent counts. To share the state itself, lift it up and pass it down instead.

Your job is to extract the counter logic into a custom hook.

Challenge

Counter logic is written straight into the component, and it should live in a hook you can reuse. Export an App component from App.jsx that uses a custom useCounter hook to keep a count, and renders a button labelled Count: 0 that increments it.

The Test clicks the button once and looks for the label to read Count: 1. The starter never changes the count, so the Test fails. Move the counter logic into the hook.

App.jsx
export function App() {
  return <button>Count: 0</button>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.