Loading lessons...
Building Custom Hooks
Building Custom Hooks
When two or more components need to share non-visual stateful logic (such as tracking window size, handling form inputs, or fetching API data), you can extract that logic into a Custom Hook.
What is a Custom Hook?
A Custom Hook is a JavaScript function whose name starts with use and that calls other React Hooks (useState, useEffect, etc.).
Custom Hooks allow you to share stateful logic across components without duplicating code or adding complex wrapper hierarchy trees.
Creating a useOnlineStatus Custom Hook
Let's build a custom hook that monitors the browser's internet connection status using browser navigator.onLine events.
// src/hooks/useOnlineStatus.js
import { useState, useEffect } from 'react';
export function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline; // Returns boolean online status
}
Consuming the Custom Hook in Components
Once defined, import and call your Custom Hook inside any functional component just like built-in React hooks.
import { useOnlineStatus } from './hooks/useOnlineStatus';
function StatusBar() {
const isOnline = useOnlineStatus();
return (
<div className={"status-bar " + (isOnline ? 'online' : 'offline')}>
{isOnline ? "✅ Connected to Network" : "❌ Disconnected (Offline)"}
</div>
);
}
Custom Hooks share stateful logic, NOT state itself. Each component that calls a custom hook gets its own completely isolated copy of state variables.
Summary & TL;DR
- Custom Hooks start with the prefix
use(e.g.,useFetch,useLocalStorage). - Custom Hooks combine built-in hooks to package reusable non-visual logic.
- Calling a custom hook inside two different components gives each component independent, isolated state.