34. Performance Optimization
Making React Lightning Fast
React is inherently fast thanks to the Virtual DOM. However, as applications scale, unnecessary re-renders can cause your app to feel sluggish. Performance Optimization is about telling React when it should skip its rendering process to save CPU cycles.
The Re-rendering Cascade
By default, when a parent component's state changes, React re-renders that parent and every single one of its children. If your top-level <App /> component updates a simple counter, a deeply nested <HeavyChart /> component will also re-render, even if its props didn't change.
React.memo (Caching Components)
You can wrap a child component in React.memo(). This acts as a shield. It tells React: "Do not re-render this component unless the props passed to it have actually changed."
useMemo (Caching Calculations)
If you have an expensive mathematical calculation or data-sorting function running inside your component, it will re-run on every render. useMemo caches the result of the calculation, only recalculating it if the dependencies change.
useCallback (Caching Functions)
In JavaScript, every time a component renders, all functions inside it are re-created in memory. If you pass a function down to a React.memo() child, the child will think the function is brand new every time, breaking the memoization. useCallback caches the function definition itself so its memory address stays identical across renders.
Knowledge Check
Ready to test your understanding of 34. Performance Optimization?