Avoid Using useEffect for Derived State in React

🔥 React Tip: Stop Using useEffect for Derived State🔥 Many developers reach for useEffect when they want to compute values based on props or state. This creates unnecessary re-renders and bugs. ❌ Don't do this: function Cart({ items }) { const [total, setTotal] = useState(0); useEffect(() => { setTotal(items.reduce((sum, item) => sum + item.price, 0)); }, [items]); return <div>Total: ${total}</div>; } ✅ Do this instead: function Cart({ items }) { const total = items.reduce((sum, item) => sum + item.price, 0); return <div>Total: ${total}</div>; } Why? → Eliminates an entire render cycle → No synchronization bugs → Simpler mental model → Better performance To improve performance, use memoization: function Cart({ items }) { const total = useMemo( () => items.reduce((sum, item) => sum + item.price, 0), [items] ); return <div>Total: ${total}</div>; } 💡 Rule of thumb: If you can calculate it during render, don't use useEffect to sync it into state. 𝗣𝗦: 𝗗𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗰𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗺𝗮𝘀𝘀𝗶𝘃𝗲 𝗼𝗳𝗳𝗲𝗿 𝗼𝗳 𝟵𝟯% 𝗱𝗶𝘀𝗰𝗼𝘂𝗻𝘁 𝗼𝗻 𝘁𝗵𝗲 𝗣𝗿𝗼 / 𝗟𝗶𝗳𝗲𝘁𝗶𝗺𝗲 𝗦𝘂𝗯𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻. 𝗟𝗶𝗻𝗸 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁 𝗮𝗻𝗱 𝗶𝗻 𝘁𝗵𝗲 𝗳𝗲𝗮𝘁𝘂𝗿𝗲𝗱 𝘀𝗲𝗰𝘁𝗶𝗼𝗻 𝗼𝗳 𝗺𝘆 𝗟𝗶𝗻𝗸𝗲𝗱𝗜𝗻 𝗽𝗿𝗼𝗳𝗶𝗹𝗲. #javascript #reactjs #nextjs #webdevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories