BeginnerCoder

Lesson 20 — Custom toggle hook

Your own hook

A custom hook is a function whose name starts with use and that calls other hooks inside. It lets several components share the same logic. useToggle keeps a boolean and returns it together with a function that flips it.

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

setN((x) => x + 1) uses the previous value, which is the safe way to update from the old one.

Note: Next.js pages are React components, so this preview runs your code with plain React in the browser. Next.js-only features (the file router, server rendering, data fetching on the server) are not running here — where a lesson needs them, it shows a small simulation instead.

Why it matters: clean components and logic you can reuse and test on its own.

Want it another way?
Task

Write the body of useToggle with useState, so the menu starts open and each click flips it.

← Back
Next →
Test your knowledge

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

Enjoying this lesson? Share it.

Keep going with Next.js 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.