BeginnerCoder

Lesson 20 — Custom hooks

Write your own hook

A custom hook is a normal function whose name starts with use and that calls other hooks inside. It packages stateful logic so any component can reuse it. Each component that calls the hook gets its own copy of the state.

function useCounter(start) {
  const [n, setN] = useState(start);
  return [n, () => setN((x) => x + 1)];
}

Why it matters: toggles, form fields and data loading become one-line hooks instead of repeated code.

Want it another way?
Task

Finish useToggle. Details should show/hide "Here are the details", and Theme should switch dark → light.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with React Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.