Prevent Unnecessary React Re-Renders with Stable References

most React developers don't know why their components re-render more than they should. they blame React. they blame performance. they don't blame their own code. the real problem: objects and arrays created inside render. every single render creates a new reference. children receive new props. they re-render unnecessarily. why it matters: React compares props. if props change, child re-renders. but if you're creating the same object every render, React thinks it changed. performance tanks. the hidden cost: one parent component creating new object = entire subtree re-renders. multiply that across your app and it adds up fast. the solution: create objects outside render. if you must create inside, use useMemo. stable references prevent unnecessary re-renders. the pattern: stable reference = child doesn't re-render. new reference = child re-renders even if data is identical. #reactjs #typescript #webdevelopment #buildinpublic #javascript

  • text

Heads up! useMemo only creates a stable reference. For it to actually stop the re-render, the Child component must be wrapped in React.memo(). Without it, the child re-renders regardless!

Hey! Good point on referential identity. I think the key nuance is that this only matters when React is actually doing a shallow comparison (React.memo, dependencies, etc). Without that, the child will re-render anyway. So it’s less about “don’t create objects in render” and more about “know when reference stability matters”. Otherwise, it can easily turn into unnecessary memoization...

Like
Reply

You don’t need useMemo in this example because the object is static. Just declare it outside the component, and it will keep a stable reference. Also, useMemo has overhead, so use it intentionally.

Why is it trendy to talk about memoisation when we finally have react compiler to do the job for us ?

This happens too when you have custom hooks that expose several values like loading, state, error and data and callbacks. Although it feels annoying at times i prefer that than debugging why a use effect is firing when it shouldn’t. Also avoid use effect as much as possible

Like
Reply

useMemo is a very expensive operation. So it shouldn't be used just for simple objects or variables... If the operation is complex, then useMemo is the right track. But, for example, to understand people, it's ok.

Like
Reply

I blame React. It shouldn’t be so counterintuitive. I guess that’s because it’s just a hack on top of HTML and JS.

Phele khud to Sikh le react. Kuch bhi daal de raha he

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories