Hey DEV community! π React hooks like useState, useEffect, useMemo, and useCallback help you write efficient, maintainable apps.
ποΈ useState: Manage Local Component State
-> useState lets you add state to functional components.
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
β When to use:
Store and update simple UI state
Track values like input fields, counters, toggles
π useEffect: Handle Side Effects
-> useEffect lets you perform side effects like data fetching, subscriptions, or DOM updates outside of render.
useEffect(() => {
console.log('Component mounted or updated!');
return () => console.log('Cleanup on unmount or before next effect!');
}, []);
β When to use:
Fetch data from APIs
Subscribe/unsubscribe to events
Update document titles, etc.
β‘ useMemo: Optimize Expensive Calculations
-> useMemo memoizes the result of a heavy computation, recomputing only when dependencies change.
const expensiveValue = useMemo(() => heavyCalculation(data), [data]);
β When to use:
Avoid recalculating values every render
Speed up components with costly computations
π useCallback: Keep Functions Stable Across Renders
-> useCallback memoizes a function, preventing it from being recreated every render if dependencies havenβt changed.
const handleClick = useCallback(() => {
console.log('Button clicked!');
}, []);
β When to use:
Pass stable functions to child components
Prevent unnecessary re-renders
π Summary
-> useState: Manage component state
-> useEffect: Handle side effects
-> useMemo: Memoize expensive computations
-> useCallback: Keep function references stable
π Thatβs it! Master these hooks to build fast, clean, and maintainable React apps. Whatβs your favorite React hook? Share below! ππ¬
Top comments (0)