React Custom Hooks
25 April 2025 | Category: React Js
What Are Custom Hooks?
In React, Custom Hooks are functions that start with the word use
and allow you to reuse stateful logic across components.
Think of them like your own versions of useState
, useEffect
, or useRef
, created to solve repeated patterns in your app.
✅ Why Use Custom Hooks?
Here’s why custom hooks are powerful:
- ♻️ Reusability: Avoid repeating the same logic in multiple components.
- 🧼 Clean Code: Keep components focused on rendering UI, not logic.
- 🔧 Organized Structure: Isolate side effects, state, or reusable behaviors.
- 🤝 Composable: Combine multiple hooks to create complex behavior.
🔧 How to Create a Custom Hook
✅ Step-by-Step:
- Create a function starting with the word
use
- Use built-in hooks inside it like
useState
,useEffect
, etc. - Return whatever values or functions you want to use in components
📌 Example 1: useWindowWidth
– Track window width
import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
👇 Using it in a component:
function App() {
const width = useWindowWidth();
return <h2>Window width: {width}px</h2>;
}
📌 Example 2: useFetch
– Custom data fetching hook
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetch(url)
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
});
}, [url]);
return { data, loading };
}
👇 Using useFetch
in a component:
function Users() {
const { data, loading } = useFetch('https://jsonplaceholder.typicode.com/users');
if (loading) return <p>Loading...</p>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
🎯 Best Practices for Custom Hooks
✅ Always start hook names with use
✅ Use other hooks inside (like useState
, useEffect
)
✅ Isolate reusable logic only, not UI
✅ Return what’s needed (state, functions, etc.)
✅ Keep them pure and predictable
📋 Summary Table
Feature | Description |
---|---|
Custom Hook | A reusable function with logic using React Hooks |
Starts with | use |
Uses built-in hooks | Like useState , useEffect , etc. |
Improves | Code reusability and readability |
Returns | Data, state, or functions |
🔥 Real-World Custom Hook Ideas
useLocalStorage
– Get/set localStorage datauseToggle
– Toggle boolean state (e.g., modal open/close)useForm
– Handle input values and validationusePrevious
– Track the previous value of a variableuseDebounce
– Delay updates to prevent rapid state changes