Custom Hooks
A custom hook is a JavaScript function whose name starts with `use` and that can call other hooks. Custom hooks let you extract and reuse stateful logic across components.
They don't share state between components โ each call gets its own independent state โ but they let you share the logic itself.
Creating a custom hook
Extract repeated logic (like fetching data or tracking window size) into a function named `useSomething` that uses built-in hooks internally.
Why use them?
Custom hooks keep components clean by moving reusable logic out, and make that logic easy to test in isolation.
import { useState, useEffect } from "react";
function useOnlineStatus() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
window.addEventListener("online", update);
window.addEventListener("offline", update);
return () => {
window.removeEventListener("online", update);
window.removeEventListener("offline", update);
};
}, []);
return online;
}
function StatusBadge() {
const online = useOnlineStatus();
return <span>{online ? "Online" : "Offline"}</span>;
}Online (updates automatically)useOnlineStatus encapsulates reusable connectivity-tracking logic.
Key points
- Custom hooks are functions starting with 'use' that call other hooks.
- They let you reuse stateful logic across multiple components.
- Each component using a custom hook gets independent state.
- Custom hooks improve testability and readability.
