π£ React Custom Hooks β Build Reusable Logic for Functional Components (2025 Guide)
π§² Introduction β Why Use Custom Hooks?
In React.js, hooks like useState, useEffect, and useContext provide powerful features within functional components. But as apps grow, you may notice repeated patterns across components β like fetching data, form handling, or toggling state.
Thatβs where Custom Hooks come in.
Custom Hooks let you extract and reuse logic across multiple components, keeping your code clean, modular, and maintainable.
π― In this guide, youβll learn:
- What custom hooks are and how to create them
- When and why to use them
- Real-world examples (toggle, fetch, form)
- Best practices and naming conventions
π§© What Are Custom Hooks?
A custom hook is simply a JavaScript function that starts with use and uses built-in hooks inside it.
β Syntax:
function useCustomHook() {
// useState, useEffect, etc.
return something;
}
π It allows you to reuse hook logic across components without copying and pasting.
βοΈ 1. Custom Toggle Hook Example
β
useToggle.js
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [value, setValue] = useState(initial);
const toggle = useCallback(() => setValue(prev => !prev), []);
return [value, toggle];
}
β Usage:
const [isOpen, toggleOpen] = useToggle();
β Perfect for dropdowns, modals, tooltips, etc.
π 2. Custom Fetch Hook (API Request)
β
useFetch.js
import { useState, useEffect } from 'react';
export function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);
return { data, loading, error };
}
β Usage:
const { data, loading, error } = useFetch('/api/users');
β Abstracts API logic into one reusable hook
π§Ύ 3. Custom Form Hook
β
useForm.js
import { useState } from 'react';
export function useForm(initialValues = {}) {
const [values, setValues] = useState(initialValues);
const handleChange = e => {
const { name, value } = e.target;
setValues(prev => ({ ...prev, [name]: value }));
};
const reset = () => setValues(initialValues);
return { values, handleChange, reset };
}
β Usage:
const { values, handleChange, reset } = useForm({ name: '', email: '' });
β Simplifies controlled form inputs and state resets
π§ 4. Why Custom Hooks Are Powerful
| Benefit | Description |
|---|---|
| β»οΈ Reusability | Share stateful logic across components |
| π§Ό Clean Code | Eliminate duplication and improve readability |
| π§ Composition | Hooks can call other hooks β logic is modular |
| π¦ Abstraction | Encapsulate complex behavior into readable units |
| π Isolation | Keeps concerns separate and testable |
π 5. Rules for Custom Hooks
β
Must start with use
β
Must follow Hooks rules:
- Only call hooks at the top level
- Only call hooks inside React functions (components or custom hooks)
β
Can use any built-in hooks (useState, useEffect, etc.)
β
Can return values, functions, or objects
π Best Practices
β
Name your custom hook descriptively: useToggle, useForm, useFetch
β
Use useCallback, useMemo inside custom hooks when needed
β
Return only whatβs needed: values, actions, booleans
β
Keep each hook single-purpose and focused
π Summary β Recap & Next Steps
Custom Hooks allow you to write cleaner, more modular code by extracting repeated logic into reusable functions. They promote consistency, simplify components, and enhance maintainability in any React application.
π Key Takeaways:
- Custom hooks are functions that use other React hooks
- Reuse logic for toggling, fetching, forms, and more
- Follow hook naming conventions (
useX) and rules - Combine multiple hooks to build advanced custom hooks
βοΈ Real-World Relevance:
Custom Hooks are widely used in production apps like Notion, Stripe, Shopify, and internal tools where component logic needs to be reused across modules.
β FAQ Section
β What makes a hook “custom”?
β
Any function that starts with use and calls built-in React hooks is considered a custom hook.
β Can I use state and effects inside a custom hook?
β
Yes! Thatβs exactly what theyβre for:
function useMyHook() {
const [count, setCount] = useState(0);
useEffect(() => { ... }, []);
}
β Can custom hooks return functions?
β
Absolutely. You can return anything: values, objects, handlers, etc.
β Can I share custom hooks between projects?
β
Yes! You can extract them into a shared hooks library or even publish them as NPM packages.
β Are custom hooks the same as HOCs or Render Props?
β No. But they replace most use cases for HOCs and Render Props in functional components.
Share Now :
