0
0
ReactHow-ToBeginner · 4 min read

How to Memoize Component in React for Better Performance

In React, you can memoize a component by wrapping it with React.memo. This tells React to skip re-rendering the component if its props have not changed, improving performance by avoiding unnecessary updates.
📐

Syntax

The basic syntax to memoize a component is to wrap it with React.memo. This creates a new component that only re-renders when its props change.

  • React.memo(Component): Wraps the component.
  • Component: The original functional component.
  • Optional second argument: a function to customize prop comparison.
javascript
const MemoizedComponent = React.memo(Component);

// Optional custom comparison function
const MemoizedComponentCustom = React.memo(Component, (prevProps, nextProps) => {
  return prevProps.someValue === nextProps.someValue;
});
💻

Example

This example shows a simple counter app where a child component is memoized. The child only re-renders when its props change, even if the parent re-renders.

javascript
import React, { useState } from 'react';

const Child = React.memo(({ count }) => {
  console.log('Child rendered');
  return <div>Count: {count}</div>;
});

export default function App() {
  const [count, setCount] = useState(0);
  const [other, setOther] = useState(false);

  return (
    <div>
      <Child count={count} />
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <button onClick={() => setOther(!other)}>Toggle Other State</button>
    </div>
  );
}
Output
When clicking 'Toggle Other State', 'Child rendered' does NOT log because props didn't change. When clicking 'Increment Count', 'Child rendered' logs because count prop changed.
⚠️

Common Pitfalls

Common mistakes when memoizing components include:

  • Memoizing components that receive new objects or functions as props every render, causing re-renders anyway.
  • Not using React.memo on functional components (it only works with functions, not class components).
  • Overusing memoization which can add complexity without performance gain.
javascript
const Child = React.memo(({ onClick }) => {
  console.log('Child rendered');
  return <button onClick={onClick}>Click me</button>;
});

// Parent recreates onClick every render, so memoization fails
function Parent() {
  const [count, setCount] = React.useState(0);
  return <Child onClick={() => setCount(c => c + 1)} />;
}

// Fix: use useCallback to memoize the function
function ParentFixed() {
  const [count, setCount] = React.useState(0);
  const handleClick = React.useCallback(() => setCount(c => c + 1), []);
  return <Child onClick={handleClick} />;
}
📊

Quick Reference

React.memo Cheat Sheet:

ConceptDescription
React.memo(Component)Wraps a functional component to memoize it.
Props comparisonBy default, shallow compares props to decide re-render.
Custom comparisonPass a function as second argument to customize prop check.
Use with functionsOnly works with functional components, not class components.
Avoid new propsAvoid passing new objects/functions each render unless memoized.

Key Takeaways

Use React.memo to wrap functional components for memoization.
Memoized components only re-render when their props change.
Avoid passing new objects or functions as props without memoizing them.
React.memo does not work with class components.
Use React.useCallback to memoize functions passed as props.