In this article I am going to discuss about the useMemo hook in react but before that if you have not gone through the useContext hook then please read that article. The useMemo hook in React is a performance optimization tool that allows developers to memoize the results of expensive computations and avoid unnecessary recalculations during re-renders. In the context of React components, useMemo takes a function and an array of dependencies as arguments, and it ensures that the function is only re-executed when one or more of the dependencies change. In simple words, we can say that useMemo hook is used to prevent unnecessary calculations or re-rendering of our components.

When to use the useMemo hook?

useMemo hook is a React Hook that lets you cache the result of a calculation between re-renders. The process of caching the result is called memoization. Therefore always use the useMemo hook at the top level of your component. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it. Let see the simple example to how we can use the useMemo hook in our react components.

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

const SquareCalculator = () => {
  const [number, setNumber] = useState(0);

  // Memoized function to calculate the square
  const calculateSquare = useMemo(() => {
    console.log('Calculating square...');
    return number * number;
  }, [number]);//Here number is passed as dependency

  return (
    <div>
      <label>
        Enter a number:
        <input
          type="number"
          value={number}
          onChange={(e) => setNumber(parseInt(e.target.value))}
        />
      </label>

      <p>Square: {calculateSquare}</p>
    </div>
  );
};

export default SquareCalculator;

In above example, the calculateSquare function is wrapped with the useMemo hook. The second argument to useMemo is an array of dependencies, in this case, the number state. The function will only be recalculated if the value of number changes. If you enter different numbers in the input field, you’ll notice that the “Calculating square…” log is only printed when the value of number changes, demonstrating the memoization effect. This helps in preventing unnecessary recalculations and improves the performance of your React components.

Conclusion

In this react hooks article I have discussed about useMemo in detail with example. Hope you found this article helpful. In the next article I am going to discuss about the useCallback hook in react. If you want to know more about the useMemo then you can go to the official documentation of react.