Skip to content

Instantly share code, notes, and snippets.

@Krishprajapati15
Created June 9, 2025 13:45
Show Gist options
  • Select an option

  • Save Krishprajapati15/7a4b5ae62cc4d91849346e89235e9455 to your computer and use it in GitHub Desktop.

Select an option

Save Krishprajapati15/7a4b5ae62cc4d91849346e89235e9455 to your computer and use it in GitHub Desktop.
This project demonstrates how to use the useMemo hook in React for optimizing performance in components with expensive calculations. The useMemo hook allows you to memoize the result of a computation so that it only recalculates when its dependencies change. This prevents unnecessary recalculations on every render, making your application more e…

React useMemo Hook Example

This project demonstrates how to use the useMemo hook in React to optimize expensive calculations and avoid unnecessary re-renders.

What is useMemo?

  • useMemo is a React Hook that memoizes the result of a computation, so it’s only recalculated when its dependencies change.
  • Purpose: Prevents expensive calculations from running on every render if the input hasn't changed.
  • Syntax:
    const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

When to Use useMemo

  • When you have a costly computation in your component that should only re-run when specific inputs change.
  • When passing objects or functions as props to child components, to avoid unnecessary re-renders.

Example: Factorial Calculator

The following component calculates the factorial of a number. The calculation is intentionally expensive to demonstrate the benefit of useMemo.

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

// Expensive factorial calculation
function factorial(n) {
  console.log("Calculating factorial...");
  if (n <= 0) return 1;
  return n * factorial(n - 1);
}

function FactorialCalculator() {
  const [number, setNumber] = useState(5);
  const [otherState, setOtherState] = useState(false);

  // Memoize the factorial calculation
  const fact = useMemo(() => factorial(number), [number]);

  return (
    <div>
      <h2>Factorial Calculator</h2>
      <input
        type="number"
        value={number}
        onChange={e => setNumber(Number(e.target.value))}
      />
      <p>Factorial: {fact}</p>
      <button onClick={() => setOtherState(!otherState)}>
        Toggle Other State
      </button>
    </div>
  );
}

export default FactorialCalculator;

Key Points

  • The factorial calculation only runs when the number changes.
  • Updating unrelated state (like otherState) does not trigger the expensive calculation again.
  • Check your browser’s developer console to see when the calculation is run.

Running the Example

  1. Clone this repository or copy the code into your React project.
  2. Import and use the FactorialCalculator component in your app.

Learn more:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment