Category: react
What Is a Custom Hook?
Published on 27 Oct 2026
Explanation
A custom Hook is a function whose name starts with use and that can call other Hooks. It lets components reuse stateful logic without sharing one state instance automatically.
Code:
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue((current) => !current);
return [value, toggle];
}
function Panel() {
const [open, toggleOpen] = useToggle();
return <button onClick={toggleOpen}>{open ? 'Close' : 'Open'}</button>;
}
Explanation
A reusable storage Hook can keep a state value synchronized with localStorage. In production, consider server rendering, JSON parsing errors, and storage availability.
Code:
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const saved = localStorage.getItem(key);
return saved === null ? initialValue : JSON.parse(saved);
} catch {
return initialValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Explanation
Debouncing delays updating a value until it has stayed unchanged for a specified duration. It is useful for reducing how often a search request is triggered while a user types.
Code:
function useDebounce(value, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
Explanation
A custom Hook can encapsulate browser event listeners and expose a simple online-status value to any component that needs it.
Code:
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;
}
Explanation
Each component calling a custom Hook gets its own Hook state. A custom Hook reuses logic; shared application-wide state needs a separate mechanism such as Context, a store, or an external state library.
Code:
function useCounter() {
const [count, setCount] = useState(0);
return { count, increment: () => setCount((c) => c + 1) };
}
function FirstCounter() {
const counter = useCounter(); // Own count
return <button onClick={counter.increment}>{counter.count}</button>;
}