Menu

Understanding Re-Renders memo, useMemo, useCallback

Understanding Re-Renders memo, useMemo, useCallback

When Does a Component Re-Render?

Three triggers:

  1. Its own state changes
  2. Its props change
  3. Its parent re-renders

The third one surprises people. When a parent re-renders, all its children re-render by default, even if their props are identical.

For most applications this is fine. React is fast, and re-rendering is not the same as updating the DOM. Optimise only when you have measured a real problem in the Profiler.

The Three Tools

React.memo - skip re-rendering a component when its props have not changed

jsx

import { memo } from "react";

const CourseCard = memo(function CourseCard({ title, progress }) {
  return (
    <div className="course-card">
      <h3>{title}</h3>
      <p>{progress}%</p>
    </div>
  );
});

export default CourseCard;

useMemo - cache an expensive calculation

jsx

import { useMemo } from "react";

const sortedCourses = useMemo(() => {
  return [...courses].sort((a, b) => b.progress - a.progress);
}, [courses]);

The sort now runs only when courses changes, not on every render.

useCallback - cache a function so its identity stays stable

jsx

import { useCallback } from "react";

const handleSelect = useCallback((courseId) => {
  setSelectedId(courseId);
}, []);

Without this, a new function is created on every render. Passing a new function to a memo-wrapped child defeats the memoisation, because the prop is technically different each time.

When to Use Each

Tool

Use when

React.memoA component re-renders often with identical props and is expensive to render
useMemoA calculation is genuinely costly sorting or filtering thousands of items
useCallbackPassing a function to a memo-wrapped child, or as a useEffect dependency

A Warning

These tools are not free. Each one adds a comparison on every render and makes the code harder to read. Wrapping every component in memo often makes an app slightly slower and much harder to maintain.

The correct order is: build it simply, measure with the Profiler, then optimise the specific thing that is slow.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details