Custom Hooks
Extract reusable stateful behavior behind a focused declarative API.
Custom hooks share stateful logic, not state itself. Each call owns independent state while following the same behavior.
Extract a browser integration
useOnlineStatus.ts
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;
}
Hooks begin with use and may call other hooks only at the top level. Design the return value around what consumers need, not internal implementation.
Choose useful boundaries
Extract a hook when several components share a meaningful behavior or when a complex integration deserves its own contract. Do not wrap every small state call.
Keep this
Extract cohesive stateful behavior, obey hook rules, hide integration details, and keep each call independent.
学习位置已保存在此设备上。