Sub topic 3
Extracting duplicated logic into a hook
This chapter assumes you know function components and JSX, props, the basics of useState and useEffect, and modern JavaScript (arrow functions, destructuring, closures). You also need the Rules of Hooks and the idea that a custom hook is a function whose name starts with use and which calls other hooks. Here you will apply that to a concrete job: finding duplicated stateful logic in components and moving it into a hook.
Spotting logic worth extracting
Two components often need the same behavior: a boolean that flips, a value that tracks a form field, a subscription. When you copy the useState call and the handler that goes with it, you have duplicated logic. Extraction means moving that code into one function that both components call.
Here are two components that repeat the same toggle logic.
import { useState } from 'react';
function Sidebar() {
const [open, setOpen] = useState(false);
const toggle = () => setOpen((value) => !value);
return (
<aside>
<button onClick={toggle}>{open ? 'Hide menu' : 'Show menu'}</button>
{open && <nav>Menu items</nav>}
</aside>
);
}
function FaqItem({ question, answer }) {
const [open, setOpen] = useState(false);
const toggle = () => setOpen((value) => !value);
return (
<section>
<button onClick={toggle}>{question}</button>
{open && <p>{answer}</p>}
</section>
);
}The state, the initial value, and the updater are identical. Only the markup differs. That split is the signal: the logic is shared, and the UI is not.
Not every repeated line is worth a hook. Extract when the repeated code:
- Calls hooks (
useState,useEffect,useRef, or other custom hooks), so a plain function cannot hold it. - Has a single, nameable purpose, such as "track a boolean" or "debounce a value".
- Appears, or is likely to appear, in more than one place, or makes one component hard to read.
The extraction steps
Extraction is a mechanical refactor. Follow the same order each time.
- Identify the lines that belong together: the state, the handlers that change it, and any effects that depend on it.
- Cut them into a new function whose name starts with
useand describes what it does. - Turn anything the logic needs from the component into parameters.
- Return whatever the component still needs to read or call.
- Replace the original lines in the component with a call to the new hook.
Applied to the toggle example, the hook looks like this.
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}The initial parameter replaces the hard-coded false. The hook returns the value and the function that changes it. The component that used to own the state now calls the hook.
import { useToggle } from './useToggle';
function Sidebar() {
const [open, toggle] = useToggle();
return (
<aside>
<button onClick={toggle}>{open ? 'Hide menu' : 'Show menu'}</button>
{open && <nav>Menu items</nav>}
</aside>
);
}
function FaqItem({ question, answer }) {
const [open, toggle] = useToggle();
return (
<section>
<button onClick={toggle}>{question}</button>
{open && <p>{answer}</p>}
</section>
);
}Each component shrank to its markup. The behavior now lives in one file you can fix once.
Why the hook is not a shared variable
A common misunderstanding is that calling useToggle in two places makes both components share one boolean. It does not. A hook shares logic. Each call to useState inside the hook attaches state to the component that is calling it.
import { useToggle } from './useToggle';
function Panels() {
const [openA, toggleA] = useToggle();
const [openB, toggleB] = useToggle();
return (
<>
<button onClick={toggleA}>{openA ? 'Hide A' : 'Show A'}</button>
<button onClick={toggleB}>{openB ? 'Hide B' : 'Show B'}</button>
</>
);
}Clicking button A changes openA only. Even inside a single component, the two calls are independent. If you want components to share one value, you need state that lives above them, such as props, context, or an external store. A custom hook alone does not do that.
Extracting a hook that has an effect
Hooks that include effects follow the same steps. Suppose a search box component debounces its input, so a request runs only after the user stops typing.
import { useState, useEffect } from 'react';
function SearchBox() {
const [text, setText] = useState('');
const [debounced, setDebounced] = useState(text);
useEffect(() => {
const id = setTimeout(() => setDebounced(text), 300);
return () => clearTimeout(id);
}, [text]);
return (
<input value={text} onChange={(e) => setText(e.target.value)} />
);
}Here the debounced state and the effect belong together. The text state belongs to the input. Draw the boundary between them: the debounce logic takes a value and a delay and gives back a delayed value. Those are the parameters and return value.
import { useState, useEffect } from 'react';
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}Two details matter during extraction:
- The hard-coded
300and thetextvariable became the parametersdelayandvalue. Both now appear in the dependency array, because the effect reads them. Before extraction,300was a constant and needed no entry. - The cleanup function moved with the effect. If you leave it behind, you get timers that fire after the value has already changed.
The component becomes simple.
import { useState } from 'react';
import { useDebouncedValue } from './useDebouncedValue';
function SearchBox() {
const [text, setText] = useState('');
const debounced = useDebouncedValue(text, 300);
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<p>Searching for: {debounced}</p>
</>
);
}Choosing parameters and return values
The shape of a hook's inputs and outputs decides how pleasant it is to use. Use these rules during extraction:
- Pass in what varies between callers. Anything that was a literal in the original component usually becomes a parameter, with a default if one value is typical.
- Return only what callers need. Hiding setters or internal flags keeps the hook easy to change later.
- Return an array for one or two values that callers will rename, as
useStatedoes. Return an object when there are several values, so callers pick by name and the order does not matter.
| Return shape | Use when | Example call |
|---|---|---|
| Array | One or two values, callers rename them | `const [open, toggle] = useToggle()` |
| Object | Three or more values, or optional ones | `const { status, data, error } = useFetchJson(url)` |
| Single value | The hook only derives something | `const debounced = useDebouncedValue(text, 300)` |
Extracting from an effect that loads data
Loading data is another common duplicate. Every component that fetches JSON tends to repeat the same loading, success, and error states. Once the logic is copied a few times, extract it. The hook below also handles a gotcha that appears as soon as the URL can change: a slow earlier request can finish after a newer one and overwrite its result.
import { useState, useEffect } from 'react';
export function useFetchJson(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => {
if (!ignore) setState({ status: 'success', data, error: null });
})
.catch((error) => {
if (!ignore && error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}The ignore flag is set by the cleanup function. When url changes, React runs the old cleanup before the next effect, so a stale response sees ignore === true and does nothing. Aborting the request also frees the network connection. The next chapters cover this pattern in more depth. For now, notice that extraction let you fix the race condition once for every caller.
A component that uses it only describes what to show.
import { useFetchJson } from './useFetchJson';
function UserCard({ id }) {
const { status, data, error } = useFetchJson(`/api/users/${id}`);
if (status === 'loading') return <p>Loading...</p>;
if (status === 'error') return <p>Failed: {error.message}</p>;
return <h2>{data.name}</h2>;
}Common extraction mistakes
Watch for these errors when you move code:
- Forgetting the
useprefix. Without it, the linter cannot check the Rules of Hooks inside your function, and other developers will not know it holds state. - Leaving a dependency behind. A value that was a closure variable in the component is now a parameter. Add it to the dependency array, or the effect reads a stale copy.
- Extracting too early. One copy of a few lines is not duplication. Wait until a second use shows what actually varies.
- Extracting a plain function as a hook. If the code calls no hooks, such as a function that formats a date, keep it a normal function. A hook adds the Rules of Hooks constraints for no benefit.
- Expecting shared state. As shown earlier, each call has its own state.
Summary of the process
- Find hook-using code that appears in more than one component.
- Move it into a
use-named function. - Turn closure variables into parameters and list them in dependency arrays.
- Return the values and functions the component needs.
- Replace the original lines with a hook call, and check that each call keeps its own state.
Exercise
A component contains const [count, setCount] = useState(0); const increment = () => setCount((c) => c + 1);, and another component has the same two lines with an initial value of 10. Write a hook that serves both, and explain what happens to count when both components are on screen at the same time.
Show answer
export function useCounter(initial = 0) { const [count, setCount] = useState(initial); const increment = useCallback(() => setCount((c) => c + 1), []); return [count, increment]; } The first component calls useCounter() and the second calls useCounter(10). Each call creates its own state, so incrementing in one component does not change the count in the other. The hook shares the logic, not the value.
Exercise
You extract an effect into a hook, and the effect used a variable delay that was previously defined in the component. The linter now warns about a missing dependency. What caused it, and what is the fix?
Show answer
Once extracted, delay is no longer a constant in the surrounding scope. It is a parameter of the hook, and the effect reads it. An effect must list every reactive value it reads, so add delay to the dependency array, for example [value, delay]. Without it, the effect would keep using the first delay it saw.