React Custom Hook Pattern
Have you ever looked at your React components and felt that while your application is getting smarter, your codebase is getting messier? You start with a simple component, but soon it’s bloated with useState and useEffect blocks managing data fetching, event listeners, or UI states.
Before React 16.8, developers relied on patterns like Higher-Order Components (HOCs) and Render Props to share stateful logic. While functional, these patterns frequently dragged developers into “wrapper hell” — deeply nested component trees that were difficult to debug, read, and maintain.
Enter the Custom Hook Pattern. This modern design pattern allows you to extract complex, stateful business logic from your presentational layout into clean, isolated, and highly reusable JavaScript functions.
What is a Custom Hook?
At its core, a custom hook is a plain JavaScript function whose name must start with the prefix use (e.g., useFetch, useToggle).
What makes it special compared to a regular utility function is its React-awareness. Inside a custom hook, you can call other built-in React hooks (like useState, useEffect, useCallback), allowing you to handle local state and side effects outside of a component structure.
The Core Rules of Hooks
To keep your UI stable, custom hooks must adhere to the fundamental rules of React hooks:
- Only Call Hooks at the Top Level: Do not call hooks inside loops, conditional blocks (
if/else), or nested inner functions. React requires hooks to execute in the exact same order on every single render. - Only Call Hooks from React Functions: Call hooks exclusively from React Functional Components or from other custom hooks — never from standard, plain JavaScript utility functions.
Real-World Example 1: The useToggle Hook (UI State Management)
Let’s start with a foundational example. Things like modals, sidebars, dropdowns, and theme configurations all share the exact same binary logic: toggling a state between true and false.
Instead of copy-pasting useState and basic switch functions everywhere, we can abstract it cleanly.
Step A: Building the Hook
Create a file named useToggle.js. This hook will manage the boolean state and export the current status alongside a static toggle function.
// src/hooks/useToggle.js
import { useState, useCallback } from 'react';
export const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
// useCallback ensures the function reference remains stable across renders
const toggle = useCallback(() => {
setValue((prev) => !prev);
}, []);
// Returning an array allows flexible naming during destructuring
return [value, toggle];
};Step B: Consuming the Hook
Now, let’s look at how elegant and readable our presentation component becomes when consuming this logic.
// src/components/ThemeSwitcher.jsx
import React from 'react';
import { useToggle } from '../hooks/useToggle';
export default function ThemeSwitcher() {
// Graceful array destructuring with semantic naming
const [isDark, toggleTheme] = useToggle(false);
return (
<div className={`p-6 min-h-screen ${isDark ? 'bg-gray-950 text-white' : 'bg-white text-black'}`}>
<h2 className="text-xl font-bold mb-2">Custom Hook Implementation</h2>
<p className="mb-4">Current Theme: <strong>{isDark ? 'Dark Mode' : 'Light Mode'}</strong></p>
<button
onClick={toggleTheme}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
>
Change UI Appearance
</button>
</div>
);
}Real-World Example 2: The useFetch Hook (Asynchronous Side Effects)
Data fetching is one of the most repetitive operations in a web app. You need to trigger an asynchronous call, manage a loading spinner state, intercept server errors, and dynamically update the data state.
Get Mr Prime’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s package that complete network architecture into a single plug-and-play hook.
Step A: Building the Hook
Create a file named useFetch.js. It takes a URL configuration parameter and updates local states depending on the life cycle of the server response.
// src/hooks/useFetch.js
import { useState, useEffect } from 'react';
export const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// Prevent execution if url is missing
if (!url) return;
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
const json = await response.json();
setData(json);
} catch (err) {
setError(err.message || 'Something went wrong');
} finally {
setLoading(false);
}
};
fetchData();
}, [url]); // Automatically refetches if the target URL changes
return { data, loading, error };
};Step B: Consuming the Hook
Instead of writing 25+ lines of network lifecycle code directly in our visual interface, we can fetch users in just a couple of lines.
// src/components/UserList.jsx
import React from 'react';
import { useFetch } from '../hooks/useFetch';
export default function UserList() {
const { data: users, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
if (loading) return <div className="text-center p-4">Fetching database profiles...</div>;
if (error) return <div className="text-red-500 text-center p-4">Error: {error}</div>;
return (
<div className="max-w-md mx-auto p-4 bg-slate-50 rounded-lg shadow">
<h3 className="font-bold text-lg border-b pb-2 mb-3">Active Corporate Directory</h3>
<ul className="space-y-2">
{users?.map((user) => (
<li key={user.id} className="p-2 bg-white rounded border hover:shadow-sm transition">
<p className="font-medium text-slate-800">{user.name}</p>
<p className="text-xs text-slate-500">{user.email}</p>
</li>
))}
</ul>
</div>
);
}Production Checklist: Avoiding Anti-Patterns
While custom hooks are incredibly liberating, keep these rules in mind to avoid common architectural pitfalls:
- Do Not Overengineer: Not every trivial piece of code needs a custom hook. If a calculation or state variable is used exclusively inside one small component, keep it there. Only abstract when you see repeated patterns or need to break up a monster component.
- Write Proper Side Effect Cleanups: If your custom hook attaches global document event listeners (e.g., tracking scroll positions or checking window sizes via
window.addEventListener), always return a cleanup function inside youruseEffectblock to remove it, preventing silent memory leaks. - Keep Dependencies Honest: When utilizing hooks like
useEffect,useCallback, oruseMemoinside your custom hooks, maintain an accurate dependency array. Missing dependencies lead to stale closures and impossible-to-trace state bugs.
Summary
The Custom Hook pattern separates the what (presentation layer) from the how (business logic engine). By incorporating this paradigm into your development workflow, you ensure your React components stay declarative, thin, and highly testable.
What logic are you planning to extract into your next custom hook? Happy coding!



