Custom hooks are JavaScript functions that let you extract and reuse stateful logic using React’s built-in hooks (useState, useEffect, etc.).
They:
- Start with the prefix
use - Follow the Rules of Hooks
- Do not return JSX (they return data or functions)
🧠 Why Use Custom Hooks?
Custom hooks solve common problems:
✔ Avoid duplicate logic
✔ Improve code readability
✔ Share logic across components
✔ Cleaner separation of concerns
✔ Easier testing and maintenance
🧪 Simple Example (Without Custom Hook)
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("/api/users")
.then(res => res.json())
.then(setUsers);
}, []);
return <div>{users.length}</div>;
}
Now imagine repeating this logic in multiple components ❌
✅ Same Logic Using a Custom Hook
Create the custom hook
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData);
}, [url]);
return data;
}
Use it in a component
function UserList() {
const users = useFetch("/api/users");
return <div>{users?.length}</div>;
}
✔ Clean
✔ Reusable
✔ No duplication
🔑 Rules for Creating Custom Hooks
1️⃣ Name must start with use
2️⃣ Call hooks only at the top level
3️⃣ Call hooks only inside:
- React components
- Other custom hooks
🔥 More Real-World Examples
✔ Form Handling Hook
function useInput(initialValue) {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: e => setValue(e.target.value),
reset: () => setValue("")
};
}
✔ Window Resize Hook
function useWindowSize() {
const [size, setSize] = useState(window.innerWidth);
useEffect(() => {
const handler = () => setSize(window.innerWidth);
window.addEventListener("resize", handler);
return () => window.removeEventListener("resize", handler);
}, []);
return size;
}
❌ What Custom Hooks Are NOT
- ❌ Not components
- ❌ Not used for rendering UI
- ❌ Not a replacement for Redux
🎯 Short Interview Answer
Custom hooks are reusable functions that extract stateful logic from components using built-in React hooks.
They help eliminate duplication, improve readability, and share logic across components while following the rules of hooks.
⭐ One-Line Summary
Custom hooks let you reuse logic, not UI.