Sub topic 3
Extracting duplicated logic into a hook
This chapter assumes you know function components, useState, and the Rules of Hooks from earlier in the tutorial. You should also be comfortable with useCallback and arrow functions.
Spotting logic worth extracting
Two components often repeat the same state and the same update function. Here both Sidebar and Details track an open/closed flag:
import { useState } from 'react';
function Sidebar() {
const [open, setOpen] = useState(false);
return (
<aside>
<button onClick={() => setOpen((value) => !value)}>
{open ? 'Close menu' : 'Open menu'}
</button>
{open && <nav>Menu items</nav>}
</aside>
);
}
function Details({ text }) {
const [open, setOpen] = useState(false);
return (
<section>
<button onClick={() => setOpen((value) => !value)}>
{open ? 'Hide' : 'Show'}
</button>
{open && <p>{text}</p>}
</section>
);
}The markup differs, but the lines that create open and flip it are identical. That repeated stateful logic is what a custom hook is for. The JSX is not part of it.
The extraction steps
- Pick the lines that belong together: the state, any effects, and the functions that update them.
- Move them into a new function whose name starts with
use. - Turn any values that differed between the copies into parameters.
- Return only what the components read or call.
- Replace the original lines with a call to the new hook.
Applying this gives the hook below. The initial value becomes a parameter with a default, and the updater is wrapped in useCallback so its identity stays the same between renders.
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}Both components now shrink to the parts that actually differ:
import { useToggle } from './useToggle';
function Sidebar() {
const [open, toggle] = useToggle();
return (
<aside>
<button onClick={toggle}>{open ? 'Close menu' : 'Open menu'}</button>
{open && <nav>Menu items</nav>}
</aside>
);
}
function Details({ text }) {
const [open, toggle] = useToggle();
return (
<section>
<button onClick={toggle}>{open ? 'Hide' : 'Show'}</button>
{open && <p>{text}</p>}
</section>
);
}Why a hook and not a component
A component shares markup and the logic behind it together. A hook shares only the logic, so each caller keeps full control of what it renders. If the duplicated part is mostly JSX, extract a component. If it is state, effects, or event handling, extract a hook.
Common errors
- Dropping the
useprefix. Naming the functiontogglestill runs, but the linter no longer checks the Rules of Hooks inside it. Conditional calls then slip through. - Hardcoding a value that differed between copies. If one caller needed
trueinitially, the hook must accept it as an argument. - Returning everything. Expose
[on, toggle], not internal setters you did not intend callers to use. - Extracting too early. Wait until the duplication is real. A hook used in one place only adds indirection.
Exercise
Two components both declare const [query, setQuery] = useState('') and a reset function that calls setQuery(''). Describe how you would extract this into a hook. Give the hook's name, its parameter, and what it returns.
Show answer
Create useQuery(initial = '') (any name starting with use that describes the purpose works). Inside it, call useState(initial) and define reset with useCallback(() => setQuery(initial), [initial]). Return [query, setQuery, reset]. Each component then calls const [query, setQuery, reset] = useQuery();. The initial value becomes a parameter so callers can start with a different string, and reset goes back to that value.