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.
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.
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 };