01
Overview
Custom hooks are functions starting with use that call other hooks. Extract reusable stateful logic. Compose hooks. Return values or state. Name: useSomething. Can use useState, useEffect, useContext, etc.
bash
function useLocalStorage(key,init){
const [val,setVal]=useState(()=>{
const s=localStorage.getItem(key);
return s?JSON.parse(s):init;
});
useEffect(()=>{localStorage.setItem(key,JSON.stringify(val));},[val]);
return [val,setVal];
}
// Usage: const [name,setName]=useLocalStorage("name","");02
Best Practices
Name with use prefix. Keep hooks focused (single responsibility). Return tuples or objects. Test with renderHook. Extract to separate files. Compose hooks freely. Document params and returns. Use for data fetching, timers, subscriptions.)
Ready to try Custom Hooks?
Visit the official site for the latest version and full documentation.
Visit Custom Hooks