React.memo Performance Optimization in React

React.memo — The Most Misunderstood Performance Optimization in React Most developers think `React.memo` makes a component faster. It does not. `React.memo` does not make your component render faster. It stops React from rendering a component when nothing has changed. And that is a huge difference. Imagine this: function Parent() { const [count, setCount] = useState(0); return ( <> <button onClick={() => setCount(count + 1)}> Increment </button> <Child /> </> ); } function Child() { console.log("Child rendered"); return <h1>I never change</h1>; } Every time you click the button: * Parent re-renders * Child re-renders * Console logs again Even though `Child` never changed. That is wasted work. Now use `React.memo`: const Child = React.memo(function Child() { console.log("Child rendered"); return <h1>I never change</h1>; }); Now when the parent re-renders, React compares the previous props and new props of `Child`. If the props are the same, React skips rendering the component. That means: * Less rendering * Less work for React * Better performance in large apps What actually happens internally? `React.memo` does a shallow comparison. That means React checks: prevProps === nextProps For primitive values like: name="Durgesh" age={22} it usually works perfectly. But for objects and functions: <Child user={{ name: "Durgesh" }} /> This will STILL re-render. Because every render creates a new object reference. Same problem with functions: <Child onClick={() => console.log("Hello")} /> That function is recreated every render. So `React.memo` thinks the props changed. Which means your optimization fails. This will NOT work const Child = React.memo(({ user }) => { console.log("Rendered"); return <h1>{user.name}</h1>; }); <Child user={{ name: "Durgesh" }} /> Because `user` is a new object every render. This WILL work const user = useMemo(() => ({ name: "Durgesh" }), []); <Child user={user} /> Now the object reference stays the same. So `React.memo` can skip the render. When should you use React.memo? Use it when: * The component renders often * The component is expensive to render * The props rarely change * You have large lists or complex UI When should you NOT use it? Do NOT wrap every component with `React.memo`. Because `React.memo` also has a cost. React now has to compare props every render. For tiny components, that comparison may cost more than simply rendering. The biggest mistake developers make is this: They use `React.memo` everywhere without checking if the component was actually re-rendering unnecessarily. First use React DevTools Profiler. Measure. Then optimize. Because performance optimization is not about adding more code. It is about stopping useless work. And that is exactly what `React.memo` does. #react #reactjs #javascript #frontend #webdevelopment #performance

  • graphical user interface

To view or add a comment, sign in

Explore content categories