Optimizing React Performance with useMemo & useCallback

🚀 React Series Part 9: Optimizing Performance with useMemo & useCallback By now, we know: 👉 React re-renders when state or props change But here’s something subtle 👇 ⚠️ Even when nothing visibly changes, React may still do extra work 💡 Where does the problem come from? On every render: • Functions are recreated • Objects/arrays get new references • Expensive calculations run again 👉 React compares props using reference equality (===) So even if data looks the same: ❗ New reference = React thinks it changed 🔥 useMemo - Avoid Recomputing Expensive Values const filteredList = useMemo(() => {  return items.filter(item => item.active); }, [items]); 📌 Without useMemo: 👉 Filter runs on every render 📌 With useMemo: 👉 Runs only when items changes 💡 When is this actually useful? ✔ Large lists (filtering, sorting) ✔ Heavy calculations ✔ Derived state ❌ Not needed for simple values 🔥 useCallback - Prevent Unnecessary Child Re-renders const handleClick = useCallback(() => {  doSomething(); }, []); 💡 Why this matters: <Child onClick={handleClick} /> Without useCallback: 👉 New function every render 👉 Child re-renders every time With useCallback: 👉 Same function reference 👉 Child avoids unnecessary re-render 🔍 Real-world scenario Imagine: 👉 Parent re-renders due to unrelated state 👉 Child receives a function prop ❌ Without optimization → Child re-renders unnecessarily ✅ With useCallback → Child stays stable ⚠️ Important nuance (this is where devs go wrong) 👉 These hooks don’t “stop renders” 👉 They help React skip work when possible Also: ❗ Overusing them can make code harder to read ❗ They themselves have a small cost 💡 Mental Model Think of it like caching: • useMemo → caches results • useCallback → caches function references 🧠 Simple takeaway (with depth) React re-renders fast ⚡ But unnecessary work still adds up 👉 Optimize only when needed, not by default Let’s keep going 🚀 #ReactJS #Learning #frontendDev

To view or add a comment, sign in

Explore content categories