Building Custom Hooks for Reusable Logic
Quick Answer: A Custom Hook is a JavaScript function whose name starts with use and calls other React hooks inside it. It lets you extract fetching, debouncing, local storage sync, and form logic out of UI components into clean, testable code.
Imagine Meena is building a Hyderabad hospital appointment portal in React. She has three screens: Doctor Search, Lab Reports, and Pharmacy Stock.
All three screens need the same logic: wait 400 ms after typing, fetch data from the API, show a loading spinner, and remember the user's selected clinic branch.
How can Meena write that stateful logic once and reuse it cleanly across every screen?
1. Why Do We Need Custom Hooks?
The problem without custom hooks
Without custom hooks, Meena copies and pastes the same useState and useEffect blocks into every component.
Example 1: Duplicated fetch and debounce logic inside a UI component
This works for one screen, but becomes a maintenance nightmare across ten screens.
function DoctorSearch() {
const [query, setQuery] = useState("");
const [doctors, setDoctors] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// 30+ lines of timer, AbortController, and fetch boilerplate repeated in every file...
}
This setup works on day one. However, it breaks down fast as the app grows.
- If you fix a race condition bug in
DoctorSearch, you must manually fix it inLabReportstoo. - UI components grow huge and hard to read because business logic mixes with JSX.
- You cannot easily unit-test the debounce or fetch logic without rendering the whole page.
The solution: Custom Hooks (use*)
Custom Hook = a reusable function starting with use that wraps built-in hooks like useState and useEffect.
Custom hooks share stateful logic, not the state itself. When two components call the same custom hook, each component gets its own completely isolated state.
Live Flow: One Custom Hook Hub, Three Isolated Component States
Watch how Meena's hospital screens reuse the exact same hook logic while keeping independent state.
Typing "Cardio" in DoctorSearch.jsx never affects LabReports.jsx. Both run the same hook code with separate memory.
2. Four Essential Custom Hooks in Practice
Let us extract the four most common patterns in Meena's hospital portal into clean, reusable hooks.
1. Data Fetching: useFetch
Always include an AbortController inside a fetch hook. It cancels old requests if the user leaves the page or types a new search term.
Example 2: Reusable useFetch hook with cleanup
import { useState, useEffect } from "react";
export function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (!url) return;
const controller = new AbortController();
setLoading(true);
setError(null);
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error("Failed to load data");
return res.json();
})
.then((json) => setData(json))
.catch((err) => {
if (err.name !== "AbortError") setError(err.message);
})
.finally(() => setLoading(false));
return () => controller.abort();
}, [url]);
return { data, loading, error };
}
2. Debouncing: useDebounce
Debounce = waiting until the user pauses typing before running an expensive task like an API search.
Example 3: Reusable useDebounce hook
import { useState, useEffect } from "react";
export function useDebounce(value, delay = 400) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
3. Local Storage Sync: useLocalStorage
This hook works just like useState, except it automatically saves Meena's selected Hyderabad clinic branch to the browser's localStorage.
Example 4: Reusable useLocalStorage hook
import { useState, useEffect } from "react";
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const saved = window.localStorage.getItem(key);
return saved ? JSON.parse(saved) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
4. Form Logic: useForm
Instead of writing separate onChange handlers for patient name, phone, and slot time, Meena wraps them into one useForm hook.
Example 5: Reusable useForm hook
import { useState } from "react";
export function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
function handleChange(e) {
const { name, value } = e.target;
setValues((prev) => ({ ...prev, [name]: value }));
}
function resetForm() {
setValues(initialValues);
}
return { values, handleChange, resetForm };
}
Expected result: Clean DoctorSearch component using the hooks
const [branch, setBranch] = useLocalStorage("clinic_branch", "Jubilee Hills");
const debouncedQuery = useDebounce(values.query, 400);
const { data: doctors, loading } = useFetch(`/api/doctors?q=${debouncedQuery}&branch=${branch}`);
The component is now short, readable, and focused purely on displaying the UI.
3. Copy-Pasted Logic vs. Custom Hooks
| Without custom hooks | With custom hooks |
|---|---|
Same useEffect code copied into many files. |
Logic lives in one reusable use* file. |
| Bug fixes must be repeated everywhere. | Fix once, and every component benefits. |
| Hard to test without rendering full screens. | Easy to unit-test in isolation with renderHook. |
The important terms to remember
- Custom Hook = a JavaScript function starting with
usethat composes built-in React hooks. - Rules of Hooks = only call hooks at the top level of React functions, never inside loops or
ifblocks. - State Isolation = each component calling a custom hook receives its own separate state memory.
Design tip: Test your custom hooks directly using renderHook from React Testing Library. You can verify debounce timers, local storage writes, and API errors without mounting any buttons or forms.
4. Common Mistakes to Avoid
1. Thinking custom hooks share state across components
Many beginners assume calling useLocalStorage or useForm in two components syncs their in-memory state automatically. It does not; each call creates a fresh state instance.
Better approach: Use React Context, Zustand, or Redux Toolkit when multiple components must share the exact same live state.
2. Skipping the use naming prefix
If you name your hook fetchDoctors() instead of useFetchDoctors(), React's linter cannot check it for Rules of Hooks violations.
Better approach: Always start every custom hook name with lowercase use.
3. Forgetting cleanup inside useEffect
Leaving timers or fetch calls running after a component unmounts causes memory leaks and stale UI updates.
Better approach: Always return a cleanup function (like clearTimeout or controller.abort()) from your effects.
5. Interview Questions & Practice
Question 1: If two components use the same custom hook, do they share state?
What the interviewer expects: Clear understanding that custom hooks reuse logic, not state.
Strong answer: "No, they do not share state. In Meena's hospital app, if both DoctorSearch and LabReports call useDebounce, React creates a completely separate timer and state variable for each component. Only the reusable logic is shared."
Question 2: How do you test a custom hook cleanly?
What the interviewer expects: Knowledge of isolated hook testing without coupling to UI markup.
Strong answer: "I use renderHook from React Testing Library along with act(). For useDebounce, I use fake timers to advance the clock by 400 ms and assert that the returned value updates only after the delay."
What interviewers expect at different levels
- Junior developer: Knows the
use*naming rule and can extract a simpleuseToggleoruseFetchhook. - Senior developer: Handles edge cases like
AbortControllercleanup, SSR safety forlocalStorage, and unit testing withrenderHook. - Technical architect: Knows when to keep logic in a custom hook vs. moving to dedicated libraries like TanStack Query or React Hook Form.
Beginner: UPI payment app
Build a useOnlineStatus() hook that listens to browser online and offline events so a UPI app warns users before they tap Pay.
Expected result: Returns true or false and cleans up event listeners on unmount.
Intermediate: Food delivery app
Combine useDebounce and useFetch to build a restaurant search bar that only calls /api/restaurants 500 ms after the user stops typing.
Hint: Pass the debounced string into the URL parameter of useFetch.
Advanced: Railway ticket portal
Upgrade useLocalStorage so that if a user opens two browser tabs and changes their station filter in Tab 1, Tab 2 updates automatically.
Challenge: Listen to the browser's storage event inside a useEffect hook.
6. Next Steps
- Refactor one repetitive
useEffectin your current React project into a reusableuse*file inside asrc/hooks/folder. - Write one unit test for
useDebounceusing Vitest andrenderHookto verify the delay works as expected.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.