React Custom Hooks for Reusable Stateful Logic
Learn how React custom hooks reuse stateful logic, follow use* naming and call rules, type inputs and results, and keep each call's state independent.
A custom hook packages stateful behavior so multiple components can reuse the same logic without sharing one state instance. The typed toggle example returns a value and an action, and shows how each call remains independent. This guide also covers the Rules of Hooks, when extraction helps, and how shared state still needs an explicit owner.
React Custom Hooks for Reusable Stateful Logic
Introduction
A custom hook packages reusable behavior with React hooks. It can focus component code, but each call has its own state instance.
Custom hooks start with use, as in useToggle or useSearch, so tooling and lint rules recognize them. A hook can call built-in hooks such as useState and useEffect, or another custom hook.
This guide builds a typed hook, reviews the hook call rules, and explains when extraction makes shared behavior easier to maintain.
Build a typed toggle hook
The hook returns a boolean and an action that changes it. Calling it twice creates two independent pieces of state:
import { useState } from "react";
interface ToggleResult {
isOn: boolean;
toggle: () => void;
}
function useToggle(initialValue = false): ToggleResult {
const [isOn, setIsOn] = useState(initialValue);
return {
isOn,
toggle: () => setIsOn((current) => !current),
};
}
function Toolbar() {
const notifications = useToggle(true);
const compactMode = useToggle();
return (
<>
<button type="button" onClick={notifications.toggle}>
Notifications: {notifications.isOn ? "on" : "off"}
</button>
<button type="button" onClick={compactMode.toggle}>
Compact mode: {compactMode.isOn ? "on" : "off"}
</button>
</>
);
}
The hook reuses the update logic, not the value. Turning compact mode on does not change notifications.
Hook call rules
Call hooks at the top level of a function component or another custom hook. Do not put them inside conditions, loops, nested functions, or event handlers. React relies on calls happening in the same order on every render to match each state value with its hook.
Extract repeated behavior or state logic that benefits from a clear name. Keep one-off state local when extraction would add file-hopping without simplifying the component.
flowchart TD
A[Component calls useToggle] --> B[Hook calls useState]
B --> C[Returns this call's state and actions]
C --> D[Component renders controls]
D --> E[Click updates that state]
E --> A
Trade-Off Table
| Need | Use | Trade-off |
|---|---|---|
| One small piece of local state | Built-in useState |
Direct and easy to follow |
| Repeated state behavior across components | Custom hook | Reuses logic, but adds an abstraction to learn |
| Repeated visual structure | Shared component | Reuses markup and behavior together; less suited to logic alone |
| One-off behavior used once | Keep it in the component | Avoids an extra file or indirection |
Production Failure Scenarios
Calling useToggle() only when a feature is enabled changes hook order if the flag changes, which can cause a hook error or mismatched state. Call it unconditionally; use the flag to decide whether to show its control. Another failure comes from a mutable module-level variable used as a shared cache: separate hook calls appear independent but silently affect each other. Keep state in React or use an explicit shared store.
Common Pitfalls / Anti-Patterns
- Avoid wrappers that only rename one built-in hook without clarifying behavior.
- Keep returned values small and clearly named; separate calls own separate state.
Observability Checklist
- Inspect hook state in React DevTools and check for hook-order errors.
- Exercise initial and updated states with two consumers.
- Unmount and remount a consumer to check initialization and cleanup.
Security and Compliance Notes
Types do not validate input at runtime. Check user or network data before trusting it, and do not store secrets in client-side state. A hook does not make input safe or private.
When to Use / When NOT to Use
Extract a custom hook when repeated stateful behavior becomes easier to name and reuse outside one component. Keep one-off logic local when extraction adds indirection without improving clarity. A hook reuses behavior; it does not share state between calls.
Quick Recap Checklist
- A custom hook starts with
useand may call built-in or custom hooks. - Call hooks in a stable order at the top level.
- Reusing hook logic does not share state between calls.
- Type the hook’s inputs and return shape when it clarifies its contract.
- Extract repeated behavior when it makes components easier to read.
Interview Questions
use?The prefix identifies hooks to readers, React tooling, and lint rules, and makes hook behavior clear at the call site.
No. Each call has its own state position in the component. Logic is reused; state values stay independent.
Extract repeated behavior or state logic that gets clearer with a name. Keep one-off state local if extraction only adds indirection.
Call it at the top level of a function component or another custom hook.
- Do not call it inside a condition, loop, or event handler.
- Keep the call order stable between renders.
No. Each call gets state for that call's component and hook position.
- Two useToggle calls can hold independent booleans.
- Shared state needs an explicit owner or shared state mechanism.
It gives repeated stateful behavior a clear name and contract.
- Use it when multiple components benefit from the same logic.
- Keep one-off logic local when extraction adds only indirection.
Yes. It can return values and functions that operate on its state.
- Give each action a clear name such as
toggle. - Type the return contract when it helps callers.
The name signals hook behavior, but the function should actually follow hook rules.
- Use the prefix when it calls built-in or custom hooks.
- Do not call hooks from ordinary utility functions.
Call the hook unconditionally, then use the condition to decide what to render or do.
- This keeps the hook sequence consistent.
- Do not move the hook call inside the condition.
No. Hook parameter and return types only help at compile time.
- Validate external data before trusting it.
- Do not put secrets in client state or logs.
Further Reading
- For the underlying state behavior, see React state with useState.
- Learn when external synchronization belongs in the hook in React effects with useEffect.
- Custom hooks do not share state; compare ownership patterns in sharing state and lifting state up.
- For broader descendant sharing, read context for shared state.
- Practice hook behavior through component and interaction testing.
- Read React’s Rules of Hooks, its guide to reusing logic with custom hooks, and the useState reference.
Conclusion
Custom hooks name reusable behavior. Follow the use convention, call built-in hooks in a stable top-level order, and type the contract components need. Each call owns its state, so reuse the logic without expecting separate components to synchronize.
Category
Related Posts
Controlled Inputs and Forms in React
Learn to control form values with React state, type change and submit events, show validation feedback, and handle form data safely with TypeScript.
React Event Handling and Event Types
Learn to type React click, change, and form handlers in TypeScript, pass callbacks through props, and validate user input safely with clear examples.
React Props, Children, and Component Composition
Learn to pass data and callbacks through React props, use children for flexible layouts, and compose small components without building giant prop APIs.