Skip to content

Custom Hooks

The Course
•
20 min study

Logic you want to reuse

On Day 6 of React Beginner, a timer component started an interval in an effect and cleaned it up. Now there are two timers, Focus and Break. Copying the effect into both would work, but you'd fix every bug twice.

You've already used two custom hooks: useCards() and useBoardDispatch() on Day 3. A custom hook is a function whose name starts with use and that calls other hooks. It lets components share logic.

Two timers, one hook React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import Timer from "./Timer.jsx"; export default function App() { return ( <main> <h1>Study timers</h1> <div className="board" style={{ gridTemplateColumns: "1fr 1fr" }}> <Timer label="Focus" /> <Timer label="Break" /> </div> </main> ); } import { useState } from "react"; import { useTimer } from "./useTimer.js"; export default function Timer({ label }) { const [running, setRunning] = useState(false); const seconds = useTimer(running); return ( <section className="column"> <h2>{label}: {seconds} s</h2> <button onClick={() => setRunning(!running)} aria-label={`${running ? "Pause" : "Start"} ${label}`}> {running ? "Pause" : "Start"} </button> </section> ); } import { useEffect, useState } from "react"; // Counts seconds while running is true. export function useTimer(running) { const [seconds, setSeconds] = useState(0); useEffect(() => { if (!running) return; const id = setInterval(() => setSeconds((s) => s + 1), 1000); return () => clearInterval(id); }, [running]); return seconds; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Start both timers, then pause one. Timer.jsx just says const seconds = useTimer(running);. Everything about intervals lives in useTimer.js:

JavaScript
export function useTimer(running) {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    if (!running) return;
    const id = setInterval(() => setSeconds((s) => s + 1), 1000);
    return () => clearInterval(id);
  }, [running]);

  return seconds;
}

Each call has its own state

Both timers call useTimer, but they count independently. A custom hook shares logic, not state. Each call runs its own useState and its own useEffect, exactly as if the code were written inside the component. If you want two components to share a value, you still lift it up or use context.

The rules

  • The name starts with use. That's how React's linter knows to check the hook rules inside it, and how readers know it may hold state.
  • Call hooks at the top level of a component or another hook: not in conditions, loops or handlers. The same rule as useState.
  • Make the interface small. Take what the logic needs, return what callers need. useTimer takes running and returns seconds.

Don't make everything a hook. A helper that doesn't call any hooks, such as formatMinutes(90), is just a function; the use prefix would mislead.

Your turn

Exercise

A reset

Change useTimer to return { seconds, reset }, where reset() sets the seconds back to 0. Add a Reset button to each Timer.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import Timer from "./Timer.jsx"; export default function App() { return ( <main> <h1>Study timers</h1> <div className="board" style={{ gridTemplateColumns: "1fr 1fr" }}> <Timer label="Focus" /> <Timer label="Break" /> </div> </main> ); } import { useState } from "react"; import { useTimer } from "./useTimer.js"; export default function Timer({ label }) { const [running, setRunning] = useState(false); const seconds = useTimer(running); return ( <section className="column"> <h2>{label}: {seconds} s</h2> <button onClick={() => setRunning(!running)} aria-label={`${running ? "Pause" : "Start"} ${label}`}> {running ? "Pause" : "Start"} </button> </section> ); } import { useEffect, useState } from "react"; // Counts seconds while running is true. export function useTimer(running) { const [seconds, setSeconds] = useState(0); useEffect(() => { if (!running) return; const id = setInterval(() => setSeconds((s) => s + 1), 1000); return () => clearInterval(id); }, [running]); return seconds; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

A hook can return anything, and when it returns more than one thing, an object with named fields is easy to read at the call site. The reset function belongs inside the hook, because only the hook can see the state it changes.

Hint 2: a first step

Change the hook first and leave Timer alone. The lab reports Objects are not valid as a React child (found: object with keys {seconds, reset}), because Timer still puts the hook's result straight into its heading as if it were a number. That's your signal to change how Timer reads the hook's result, and then to give it a button that uses the new function.

Show one solution

In useTimer.js:

JavaScript
function reset() {
  setSeconds(0);
}

return { seconds, reset };

In Timer.jsx:

JavaScript
const { seconds, reset } = useTimer(running);
JSX
<button onClick={reset} aria-label={`Reset ${label}`}>Reset</button>

Each timer's Reset only resets its own count, because each call to useTimer has its own seconds.

Was this article helpful?

Your response is saved on this device.