0
0
Reactframework~5 mins

useMemo hook in React

Choose your learning style9 modes available
Introduction

The useMemo hook helps your React app remember a value so it doesn't have to recalculate it every time. This makes your app faster and smoother.

When you have a slow calculation that doesn't need to run on every render.
When you want to avoid repeating work unless some data changes.
When you want to keep the same object or array reference to prevent unnecessary updates.
When you want to optimize performance in a list or complex UI.
When you want to avoid expensive operations inside your component.
Syntax
React
const memoizedValue = useMemo(() => {
  // calculation or function
  return result;
}, [dependencies]);

The first argument is a function that returns the value you want to remember.

The second argument is an array of dependencies. The value recalculates only if these change.

Examples
Calculate double of number only when number changes.
React
const doubled = useMemo(() => number * 2, [number]);
Sort list only when list changes.
React
const sortedList = useMemo(() => [...list].sort(), [list]);
Create a config object once and reuse it forever because dependencies array is empty.
React
const config = useMemo(() => ({ theme: 'dark' }), []);
Sample Program

This example shows a component that calculates double of a number. The calculation logs a message only when the number changes. Clicking 'Toggle Other' does not recalculate because useMemo remembers the value.

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

function ExpensiveCalculation({ number }) {
  const doubled = useMemo(() => {
    console.log('Calculating double...');
    return number * 2;
  }, [number]);

  return <div>Double: {doubled}</div>;
}

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

  return (
    <main>
      <h1>useMemo Example</h1>
      <button onClick={() => setCount(c => c + 1)}>Increase Count</button>
      <button onClick={() => setOther(o => !o)}>Toggle Other</button>
      <p>Count: {count}</p>
      <p>Other: {other.toString()}</p>
      <ExpensiveCalculation number={count} />
    </main>
  );
}
OutputSuccess
Important Notes

Don't use useMemo to fix bugs or for every value. Use it only when performance matters.

Remember to include all variables used inside the function in the dependencies array.

Logging inside useMemo helps see when it recalculates.

Summary

useMemo remembers a value between renders to avoid repeating work.

It recalculates only when dependencies change.

Use it to speed up slow calculations or keep stable references.