1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. React Memo
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
06Hrs
27Mins
08Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. React Memo

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
06Hrs
27Mins
08Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

React.memo

Overview

By default, React uses a very simple rule for rendering: If a Parent component re-renders, ALL of its children re-render recursively, regardless of whether the child's specific props actually changed.

In most apps, this is completely fine because React's Virtual DOM diffing is incredibly fast. However, if a child component is extremely heavy (like a Data Grid rendering 5,000 rows, or a complex SVG chart), re-rendering it every time the parent updates a completely unrelated state (like a tiny text input) will cause massive lag.

To prevent this, you can wrap the heavy child component in `React.memo` (short for memoization). React.memo tells React: 'Before you re-render this child, look at its props. If the props are exactly the same as they were during the last render, skip this component entirely and reuse the old HTML.'

Syntax

Wrapping a Heavy Component
javascript
import { memo, useState } from 'react';

// 1. We wrap the component export in memo()
const ExpensiveChart = memo(function ExpensiveChart({ data }) {
  // Imagine this takes 500ms to calculate and render
  console.log("Chart is rendering!");
  return <div className="heavy-chart">...</div>;
});

function Dashboard() {
  const [text, setText] = useState('');
  const [chartData, setChartData] = useState([1, 2, 3]);

  return (
    <div>
      {/* 2. Typing in this input updates 'text', causing Dashboard to re-render. */}
      {/* WITHOUT memo, ExpensiveChart would re-render on every single keystroke! */}
      {/* WITH memo, React sees 'chartData' hasn't changed, and skips the chart render. */}
      <input value={text} onChange={(e) => setText(e.target.value)} />
      
      <ExpensiveChart data={chartData} />
    </div>
  );
}

Common Pitfalls

  • Overusing React.memo: Do NOT wrap every single component in memo. Running the prop comparison equation actually costs CPU time. If a component is lightweight (like a simple Button or text block), the prop comparison often takes longer than just letting React re-render the component. Only use memo when profiling proves a specific component is causing noticeable lag.

Interview Questions

What kind of prop comparison does React.memo perform?

React.memo performs a shallow comparison (===) of the props. This means if you pass a primitive (string, number), it works perfectly. But if you pass a newly created object or array (data={[1, 2, 3]}), the shallow comparison will always fail (because the memory reference is new), and the component will re-render anyway, completely defeating the purpose of memoization.

How can you fix a React.memo that is breaking due to complex object props?

You have two options. You can either use useMemo/useCallback in the parent to ensure the object/function memory reference doesn't change, OR you can pass a custom comparison function as the second argument to React.memo, manually telling React exactly how to compare the old and new props.

Real-World Example

Memoizing a Data Grid Row: Large lists and data grids are the #1 use case for React.memo. When dealing with thousands of nodes, skipping render cycles is critical to maintaining a 60 FPS scroll and interaction rate.

example
javascript
import { memo } from 'react';

// In a table with 10,000 rows, editing Row #5 causes the Parent Table to re-render.
// Without memo, React would re-render all 10,000 rows just to update 1.
// With memo, React instantly skips the 9,999 rows that haven't changed.
const TableRow = memo(({ rowData, onEdit }) => {
  return (
    <tr>
      <td>{rowData.id}</td>
      <td>{rowData.name}</td>
      <td>{rowData.status}</td>
      <td><button onClick={() => onEdit(rowData.id)}>Edit</button></td>
    </tr>
  );
});

export default TableRow;

Check Your Knowledge

Test your understanding of React.memo with these quick questions.

Question 1

What determines whether a component wrapped in `React.memo` will re-render?

Question 2

Why shouldn't you wrap every component in your app with `React.memo`?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

React.memo

Overview

By default, React uses a very simple rule for rendering: If a Parent component re-renders, ALL of its children re-render recursively, regardless of whether the child's specific props actually changed.

In most apps, this is completely fine because React's Virtual DOM diffing is incredibly fast. However, if a child component is extremely heavy (like a Data Grid rendering 5,000 rows, or a complex SVG chart), re-rendering it every time the parent updates a completely unrelated state (like a tiny text input) will cause massive lag.

To prevent this, you can wrap the heavy child component in `React.memo` (short for memoization). React.memo tells React: 'Before you re-render this child, look at its props. If the props are exactly the same as they were during the last render, skip this component entirely and reuse the old HTML.'

Syntax

Wrapping a Heavy Component
javascript
import { memo, useState } from 'react';

// 1. We wrap the component export in memo()
const ExpensiveChart = memo(function ExpensiveChart({ data }) {
  // Imagine this takes 500ms to calculate and render
  console.log("Chart is rendering!");
  return <div className="heavy-chart">...</div>;
});

function Dashboard() {
  const [text, setText] = useState('');
  const [chartData, setChartData] = useState([1, 2, 3]);

  return (
    <div>
      {/* 2. Typing in this input updates 'text', causing Dashboard to re-render. */}
      {/* WITHOUT memo, ExpensiveChart would re-render on every single keystroke! */}
      {/* WITH memo, React sees 'chartData' hasn't changed, and skips the chart render. */}
      <input value={text} onChange={(e) => setText(e.target.value)} />
      
      <ExpensiveChart data={chartData} />
    </div>
  );
}

Common Pitfalls

  • Overusing React.memo: Do NOT wrap every single component in memo. Running the prop comparison equation actually costs CPU time. If a component is lightweight (like a simple Button or text block), the prop comparison often takes longer than just letting React re-render the component. Only use memo when profiling proves a specific component is causing noticeable lag.

Interview Questions

What kind of prop comparison does React.memo perform?

React.memo performs a shallow comparison (===) of the props. This means if you pass a primitive (string, number), it works perfectly. But if you pass a newly created object or array (data={[1, 2, 3]}), the shallow comparison will always fail (because the memory reference is new), and the component will re-render anyway, completely defeating the purpose of memoization.

How can you fix a React.memo that is breaking due to complex object props?

You have two options. You can either use useMemo/useCallback in the parent to ensure the object/function memory reference doesn't change, OR you can pass a custom comparison function as the second argument to React.memo, manually telling React exactly how to compare the old and new props.

Real-World Example

Memoizing a Data Grid Row: Large lists and data grids are the #1 use case for React.memo. When dealing with thousands of nodes, skipping render cycles is critical to maintaining a 60 FPS scroll and interaction rate.

example
javascript
import { memo } from 'react';

// In a table with 10,000 rows, editing Row #5 causes the Parent Table to re-render.
// Without memo, React would re-render all 10,000 rows just to update 1.
// With memo, React instantly skips the 9,999 rows that haven't changed.
const TableRow = memo(({ rowData, onEdit }) => {
  return (
    <tr>
      <td>{rowData.id}</td>
      <td>{rowData.name}</td>
      <td>{rowData.status}</td>
      <td><button onClick={() => onEdit(rowData.id)}>Edit</button></td>
    </tr>
  );
});

export default TableRow;

Check Your Knowledge

Test your understanding of React.memo with these quick questions.

Question 1

What determines whether a component wrapped in `React.memo` will re-render?

Question 2

Why shouldn't you wrap every component in your app with `React.memo`?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A