🧩 Custom Hooks in React - Explained with Examples
🔹 What is a Custom Hook?
A custom hook in React is a function that starts with use
and allows you to reuse stateful logic across components.
🔹 Why Use Custom Hooks?
- To avoid repetition of logic in multiple components
- To keep your components clean and readable
- To share behavior easily between components
🪟 Example: useWindowWidth
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;
}
export default useWindowWidth;
Usage:
import useWindowWidth from './useWindowWidth';
function MyComponent() {
const width = useWindowWidth();
return <h3>Window width: {width}px</h3>;
}
🌐 Example: useFetch
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 };
}
export default useFetch;
Usage:
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>;
⏱️ Example: useDebounce
function useDebounce(value, delay = 500) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timeout);
}, [value, delay]);
return debounced;
}
🌐 Example: useOnlineStatus
function useOnlineStatus() {
const [isOnline, setOnline] = useState(navigator.onLine);
useEffect(() => {
const goOnline = () => setOnline(true);
const goOffline = () => setOnline(false);
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
return isOnline;
}
🌙 Example: useDarkMode
function useDarkMode() {
const [enabled, setEnabled] = useLocalStorage('darkMode', false);
useEffect(() => {
document.body.classList.toggle('dark-mode', enabled);
}, [enabled]);
return [enabled, setEnabled];
}
📦 Summary
- Custom Hooks start with
use
and use other hooks inside - They return state, functions, or data — not JSX
- You can reuse them across multiple components
- Helps separate logic from UI
0 Comments