Why custom hooks
Custom hooks allow you to share stateful logic without duplicating code.
Naming rule: custom hook names must start with use.
Example: online status hook
tsx
function useOnlineStatus() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const on = () => setOnline(true);
const off = () => setOnline(false);
window.addEventListener('online', on);
window.addEventListener('offline', off);
return () => {
window.removeEventListener('online', on);
window.removeEventListener('offline', off);
};
}, []);
return online;
}Benefits
- Cleaner components
- Reusable logic
- Better testability
Next, we will implement routing.