A custom hook is a JavaScript function that starts with use and uses built-in React hooks (like useState, useEffect, etc.) to encapsulate reusable logic across multiple components.
🔹 Why Use Custom Hooks?
- ♻️ Reuse stateful logic across components
- 🧼 Keep components clean and focused
- 🔧 Separate logic from UI
- 🧪 Easier to test and maintain
🔹 How to Create a Custom Hook:
- Create a function that starts with
use. - Use built-in hooks inside it.
- Return any values or functions you want to expose.
🔹 Example: useFetch Hook
// useFetch.js
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(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
export default useFetch;
🔹 Using the Custom Hook in a Component:
import useFetch from './useFetch';
function Users() {
const { data, loading } = useFetch('https://api.example.com/users');
if (loading) return <p>Loading...</p>;
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
📝 In Summary:
- A custom hook is a reusable logic container in React built using built-in hooks.
- It helps keep your components clean, modular, and DRY (Don't Repeat Yourself).
- They’re perfect for abstracting repeated effects, state, or complex behaviors.