React Memoization: Avoiding Rerenders with Pure Components

In React, memoizing a component doesn't always prevent rerendering. We use the memo API to memoize a component to optimise performance. It is essential to understand that the memo API only works if the props remain the same and the component is pure. However, a memoised component with the following attributes will re-render. 1. The state gets set internally 2. Using a context that gets updated The memo works wrt values updated and passed from the parent, not the internal ones. By understanding it, one can avoid bugs and build reliable components. Have you noticed this behaviour earlier? #react #javascript #frontend

  • text

And another thing which sometimes is overlooked is when you pass down functions as props to a memorized component it will still rerender if the parent re-renders even if it would seem that none of the props have changed. Since functions are stored by reference and each rerender creates a new one it is registered as a prop change which causes the memorized component to rerender.

Like
Reply

Or one could use svelte and get this over with

Yes, this trips many people up. memo only protects from parent prop changes, not state or context updates.

Well said. memo optimizes prop changes, not component behavior. Internal state and context are valid rerender triggers, and misunderstanding that causes subtle bugs.

Like
Reply

SetState would be called inside this component. It makes sense to rerender the component. In order to block rerenders due context, the context needs to be memoised as well.

Yep. Most use memo like a magic trick then blame React when it doesn’t work.

Like
Reply

Memo only helps if props stay the same internal state or changing context still triggers rerenders.

Like
Reply

Spot on! React.memo only shields against prop changes from the parent. Internal state or context updates will still rerender the component, something every React dev keeps in mind when optimizing.

Like
Reply

Context matters; React’s memoization still performs full renders.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories