Skip to main content

Command Palette

Search for a command to run...

React Memorization

Updated
2 min read
React Memorization
Y
Crafting delightful applications with #React #ReactNative #NextJS #TypeScript #GraphQL

In React, when a parent component is updated, all of its child components will be rerendered even if the props are the same. It’s generally fine for simple components, but for those that perform expensive operations, there’s a performance gain in ensuring they are not rerendered unnecessarily using React memorization.

If you are using React v19, React automatically adds memoization when it’s necessary with the React Compiler. React Compiler automatically analyzes code and memoizes components and functions that it determines will never change. It can automatically optimize performance by identifying and memoizing stable parts of the application at build time. If you are working on an older codebase, you would want to understand its usage.

React.Memo

Just wrap the expensive function with it, and it will only rerender if the props change.

However, for objects and arrays, React.memo performs a shallow comparison of props. This means it only checks if the new object has the same reference in memory as the old object, not whether the contents of the objects are identical.

If the parent component creates a new object on every render, even if the new object contains the same values, the memoized child component will still rerender. So in this case, put in the second parameter to actually compare its value.

import { memo, useState } from 'react';

const MemoizedChild = memo(({ user }) => {
  // expensive operations...
  return <div>{user.name}</div>;
}, (prevProps, nextProps) => {
  // actually compare its value
  return prevProps.user.name === nextProps.user.name;
});

function Parent() {
  const [count, setCount] = useState(0);

  // A new user object is created every time Parent re-renders
  const user = { name: 'John' }; 

  return (
    <div>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <MemoizedChild user={user} />
    </div>
  );
}

React.useMemo and React.useCallback

They both compare the value of the objects listed in the dependency list. useCallback is a wrapper of useMemo, so they do the same thing, and the syntax is very similar.

const render = useMemo(() => (user) => expensiveCall(user), [user]);
const render2 = useCallback((user) => expensiveCall(user), [user]);

The idea of memorization sounds very good, but don’t overuse it. Strings and numbers should never be memoized because they are compared by value, not by pointer. Also, there is a cost to make deep comparisons at every render, and it may cause bugs by not updating the child components correctly.

More from this blog

UI Dev

18 posts

Rao Ventures Tech Blog