A Custom Hook is a JavaScript function that uses React Hooks inside it and allows you to reuse logic across multiple components.
✔ They start with use
✔ They are not part of React itself — you create them
✔ They help remove duplicate code
✔ They keep components clean and readable
🔥 Example: Custom Hook to Fetch Data
import { useEffect, useState } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
});
}, [url]);
return { data, loading };
}
export default useFetch;
Usage:
const { data, loading } = useFetch("/api/users");
✔ Reusable
✔ Clean
✔ No repeated logic
⭐ Why Use Custom Hooks?
- Reuse repeated logic (fetching, timers, forms)
- Extract complex logic out of components
- Reduce large component files
- Make testing easier
- Improve maintainability
🎯 Examples of Popular Custom Hooks
useFetch()→ fetch APIuseLocalStorage()→ persist stateuseToggle()→ boolean toggleuseDebounce()→ debounce user inputusePrevious()→ track previous state
🔥 RULES for Creating Custom Hooks
(Same rules as React Hooks)
✅ Rule 1 — Hooks must start with use
Correct:
useAuth()
useFetch()
useToggle()
Incorrect:
getData()
fetchApi()
React uses the use prefix to detect Hooks automatically.
✅ Rule 2 — Hooks must call other hooks at the top level
You cannot call Hooks inside:
❌ loops
❌ conditions
❌ nested functions
❌ if, for, while, switch
Correct usage:
function useTimer() {
const [time, setTime] = useState(0); // top level
useEffect(() => {}, []); // top level
}
✅ Rule 3 — Hooks can only be called inside:
✔ Functional components
✔ Other custom hooks
Cannot be used inside: ❌ regular functions
❌ class components
Example:
function useAuth() {
const [user, setUser] = useState(null); // allowed
}
🔶 Optional Best Practices (Important for Interviews)
✔ Keep hooks pure
Do not mutate DOM directly.
✔ Return only what's needed
Typically return:
- values
- functions
- state
- computed results
✔ One hook = one responsibility
useAuth should only handle authentication logic.
🎯 Short Interview Answer
Custom Hooks are reusable functions that contain shared stateful logic using React Hooks. They help remove duplicate logic across components.
The rules are:
- The function must start with
use.- Hooks must be called at the top level (not inside loops or conditions).
- Hooks can only be used inside React function components or other custom hooks.