Custom Hooks in React: Build Reusable Logic with 3 Examples
Learn what custom Hooks reuse, then build and test three practical Hooks for toggles, bounded quantities, and race-safe user loading.
KnowledgeGate Team
Exam prep & CS education

Copying the same useState and useEffect logic into several components feels harmless at first until you fix a bug in one copy and miss the others. Repeated behaviour can be extracted into three runnable Hooks: useToggle, bounded useQuantity, and race-safe useUser. A custom Hook is a reusable function whose name starts with use followed by a capital letter and whose body calls React Hooks.
What a Custom Hook Reuses, and What It Does Not
A ProductCard component returns UI. A formatPrice(499) helper calculates a value. A useQuantity(2, 1, 5) Hook coordinates React state or effects. A use prefix alone does not create a useful Hook contract.
The official React guide to custom Hooks makes the key distinction: custom Hooks share logic, not state. Two calls to useToggle(false) create separate state cells. Shared state still needs lifting, context, or an external store.
Extract when two components need the same state transitions, effect lifecycle, subscription, or cleanup. A one-line calculation belongs in a plain helper; React-driven logic belongs in a custom Hook. The Coding & Skill Development category connects this distinction to related front-end topics.
Example 1: Extract useToggle from Repeated UI State
A mobile menu starts closed, while a help panel starts open. Both need toggle, open, and close, so give that behaviour one contract:
import { useEffect, useState } from "react";
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
return {
value,
toggle: () => setValue(current => !current),
open: () => setValue(true),
close: () => setValue(false),
};
}
export function ToggleDemo() {
const menu = useToggle(false);
const help = useToggle(true);
return <>
<p>Menu: {menu.value ? "open" : "closed"}</p>
<button onClick={menu.toggle}>Toggle menu</button>
<p>Help: {help.value ? "open" : "closed"}</p>
<button onClick={help.close}>Close help</button>
</>;
}Initially, the text is Menu: closed and Help: open. Toggling the menu changes only the first; closing help changes only the second. A named object avoids memorised array positions. Destructuring can rename a field: const { value: isMenuOpen } = useToggle().
Worked Example: A Bounded useQuantity Hook
The next Hook owns four behaviours: increment, decrement, reset, and boundary enforcement.
function useQuantity(initialValue, min, max) {
const [quantity, setQuantity] = useState(initialValue);
return {
quantity,
increment: () => setQuantity(current => Math.min(current + 1, max)),
decrement: () => setQuantity(current => Math.max(current - 1, min)),
reset: () => setQuantity(initialValue),
};
}
function ProductQuantity() {
const item = useQuantity(2, 1, 5);
return <button onClick={item.increment}>Product: {item.quantity}</button>;
}
function CartQuantity() {
const cart = useQuantity(10, 5, 15);
return <button onClick={cart.decrement}>Cart: {cart.quantity}</button>;
}For useQuantity(2, 1, 5), the exact transitions are:
Start at
2.Four increments produce
3,4,5,5.One decrement produces
4.Reset restores the original value,
2.
The fourth increment calculates Math.min(5 + 1, 5), so it stays 5. The functional updater reads the latest committed value when React queues updates. Changing the product from 2 to 3 leaves the cart at 10, proving that reused logic keeps independent state. The complete React and Redux course develops the wider sequence.

Example 3: A Race-Safe useUser Data Hook
Promises can resolve out of request order. Per-effect cleanup prevents a stale result from winning:
const fakeUsers = {
42: { id: 42, name: "Asha" },
7: { id: 7, name: "Kabir" },
};
function loadUser(id) {
const delay = id === 42 ? 800 : 200;
return new Promise((resolve, reject) => setTimeout(() => {
fakeUsers[id]
? resolve(fakeUsers[id])
: reject(new Error(`User ${id} not found`));
}, delay));
}
function useUser(userId) {
const [result, setResult] = useState({
status: "loading", user: null, error: null,
});
useEffect(() => {
let ignore = false;
setResult({ status: "loading", user: null, error: null });
loadUser(userId).then(
user => !ignore && setResult({ status: "success", user, error: null }),
error => !ignore && setResult({ status: "error", user: null, error: error.message }),
);
return () => { ignore = true; };
}, [userId]);
return result;
}Render ID 42 at t=0, then switch to 7 at t=100 ms. Kabir's 200 ms request finishes at t=300 ms, so Kabir appears. Asha finishes at t=800 ms, but cleanup makes her result stale. Without cleanup, Asha would overwrite Kabir. ID 99 returns status: "error" and User 99 not found, guarded by the ignore check.

Design a Small, Honest Hook Contract
Name the reusable capability: useQuantity, not useProductCardQuantity; useUser, not useProfilePage. Parameters expose caller choices such as userId, min, and max. Return only needed state and actions.
A pair such as [value, setValue] can follow React's array convention. Several distinct fields favour { status, user, error }. Objects do not prevent rerenders; this is an API-readability choice.
Keep rendering in components. useUser returns status or user data; its component chooses text, a spinner, or a card. Next, explore server-side data in the Mongoose schemas, models, validation, and population guide.
Common Custom Hook Errors and Their Fixes
Calling useToggle(false) inside if (isMobile) or an onClick handler is wrong. Call it unconditionally at the top of MobileMenu; branch during rendering and invoke toggle in the handler. Custom Hooks follow built-in Hooks' call-order constraints.
In useUser, missing userId dependencies retain the first ID. Missing cleanup lets Asha replace Kabir. Fix both with [userId] and per-effect cleanup.
Two Hook calls do not share state, as quantities 2 and 10 showed. Wrapping subtotal * 0.18 in a Hook adds no value unless React state, context, an effect, or another Hook is involved.
How Interviews and Practice Exercises Test Custom Hooks
Given two components with isOpen plus open, close, and toggle handlers, extract the exact useToggle API. Explain why each top-level call owns independent state.
In a Hook test, use the renderer's update wrapper. Assert 2, increment four times and expect 5, decrement and expect 4, then reset and expect 2. Test public behaviour, not useState call counts.
Try these next:
Write
usePrevious(value). Renders with10, then14, should expose previous valuesundefined, then10.Write
useKeyPress("Escape"). Pressing Enter should leave the resultfalse; pressing Escape should set it totrue; releasing Escape should restorefalse. After unmount, the same events should produce no component update.
For adjacent front-end revision, use these HTML interview questions for freshers.
Short Version and Next Step
Extract a custom Hook when React-driven logic repeats. Keep its inputs and outputs narrow, and test the returned behaviour through exact state transitions. The logic is reused, but every call retains independent state.
Now type useToggle from memory and run false -> true -> false. Then test the bounded 2 -> 3 -> 4 -> 5 -> 5 sequence. To continue from isolated Hooks into a full application path, follow the MERN Stack course.
Keep learning
React Hooks Explained: useState, useEffect, useMemo, and Custom Hooks with Interview Questions
Build the right mental model for React Hooks, then trace a debounced search component from keystroke to filtered result.
React Components and Props Tutorial: Build Reusable UI Step by Step
Build one reusable React progress card, follow its props from parent to child, compose a panel with children, and practise by predicting exact output.
React Interview Questions for Freshers: Hooks, Reconciliation and the State Choices That Get Tested
Fresh React interviews are won by tracing renders, not reciting definitions. Learn the stale-closure trap, stable keys and a practical state-management decision rule.
Annotations in Java Tutorial: Custom Metadata, Retention and Reflection Examples
Create a custom Java annotation from zero, inspect its values through reflection, and learn how retention, targets and defaults control the result.





