← Back to Chapters

React Memoization

⚛️ React Memoization

? Quick Overview

Memoization in React is a performance optimization technique that avoids unnecessary re-renders by caching component output and reusing it when inputs remain unchanged.

? Key Concepts

  • Memoization caches component results.
  • React.memo() is used with functional components.
  • Uses shallow comparison of props.
  • Helps reduce unnecessary rendering.

? Syntax & Theory

React.memo() is a higher-order component that wraps a functional component and re-renders it only when its props change.

? Code Example — Basic Usage

? View Code Example (Button.js)
// Memoized button component that only re-renders when props change
import React from "react";

function Button({ onClick, label }) {
console.log("Rendering:", label);
return (
<button className="btn btn-primary m-1" onClick={onClick}>
{label}
</button>
);
}

export default React.memo(Button);
? View Code Example (App.js)
// Parent component demonstrating re-render behavior
import React, { useState } from "react";
import Button from "./Button";

function App() {
const [count, setCount] = useState(0);
const [name, setName] = useState("Meghraj");

console.log("App re-rendered");

return (
<div className="text-center">
<h4>Count: {count}</h4>
<Button label="Increment" onClick={() => setCount(count + 1)} />
<Button label="Say Hello" onClick={() => alert(`Hello, ${name}`)} />
</div>
);
}

export default App;

The Button component wrapped with React.memo() will only re-render when its label or onClick props change.

⚡ Custom Comparison Function

? View Code Example
// Custom comparison to control re-rendering behavior
export default React.memo(Button, (prevProps, nextProps) => {
return prevProps.label === nextProps.label;
});

The comparison function returns true to skip re-rendering and false to allow it.

? Tips & Best Practices

  • Use React.memo() for pure, stateless components.
  • Combine with useCallback() to stabilize function props.
  • Profile performance before optimizing.
  • Avoid overusing memoization unnecessarily.

? Try It Yourself

  1. Create multiple memoized button components.
  2. Track renders using console.log().
  3. Add a custom comparison function.
  4. Test shallow vs deep props.

Goal: Understand how React.memo() prevents unnecessary re-renders.