Hooks are functions that let function components use React features such as state, side effects, context and refs. Introduced in React 16.8, they replaced most class-component patterns. Core hooks - useState: local state. const [count, setCount] = useState(0); - useEffect: side effects after render (data fetching, subscriptions, timers), with cleanup. useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, []); - useContext: read values from a context provider without prop drilling. - useReducer: complex state logic with a reducer function, similar to Redux. - useRef: a mutable value that persists between renders without causing re-renders, or a reference to a DOM element. const inputRef = useRef<HTMLInputElement>(null); inputRef.current?.focus(); - useMemo and useCallback: memoise values and functions for performance. - useLayoutEffect: runs synchronously after DOM changes, before the browser paints (DOM measurements). Additional hooks - useId: stable unique IDs for accessibility attributes. - useTransition and useDeferredValue: keep the UI responsive during expensive updates. - useSyncExternalStore: subscribe to external stores. - React 19: use (read promises and context), useActionState, useFormStatus and useOptimistic for forms and optimistic UI. Rules of hooks 1. Call hooks only at the top level — not inside loops, conditions or nested functions — so React can match hook calls between renders. 2. Call hooks only from React function components or custom hooks. The eslint-plugin-react-hooks plugin enforces these rules and checks effect dependencies. Custom hooks Extract reusable stateful logic into functions starting with "use": function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const onResize = () => setWidth(window.innerWidth); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, []); return width; } Benefits of hooks: less boilerplate than classes, logic grouped by concern instead of split across lifecycle methods, easy reuse through custom hooks, and better compatibility with modern React features.
Ravindra Wadile · · 0 likes