React Hooks
useState
Local state in function components:
const [value, setValue] = useState(initialValue); setValue(newValue);
useEffect
Side effects on mount, update, unmount:
useEffect(() => {
// run on mount/update
return () => {
// cleanup on unmount
}
}, [deps]);useContext
Consume context values:
const MyContext = createContext(defaultValue);
function Component() {
const value = useContext(MyContext);
return <span>{value}</span>;
}Custom Hooks
Encapsulate logic in reusable functions:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handle = () => setWidth(window.innerWidth);
window.addEventListener('resize', handle);
return () => window.removeEventListener('resize', handle);
}, []);
return width;
}