techStackGuru

React useMemo Hook


React useMemo hook lets you optimize the performance of your components by memoizing the results of functions or computations. As a result, your application will be more efficient and dont have to re-evaluate costly calculations or data processing.

Here is the basic syntax of useMemo:

const memoizedValue = useMemo(() => {
    // Processing data or calculations
    return result;
  }, [dependency1, dependency2]); 

It takes a callback function as its first argument to perform the expensive calculation or data processing. In the memoizedValue, the result of this function is stored.

Dependencies are represented by the second argument. A new value for memoizedValue is computed whenever any of the dependencies changes. When there is no change in dependencies, the previously computed value will be returned without recalculating.

UseMemo can be useful in the following situations:

  • Calculations that are complex
  • Data that has been derived
  • Using APIs more efficiently
  • Improvements in performance
  • Reducing the need for unnecessary renderings
  • Computing Derived Data:

    import React, { useMemo } from 'react';
    
      function ExampleComponent({ data }) {
        const processedData = useMemo(() => {
          // Perform complex data manipulation or computation
          return data.map(item => item * 2);
        }, [data]);
      
        return <div>Processed Data: {processedData.join(', ')}</div>;
      } 

    Data is doubled in this example to calculate processedData. Data dependencies are computed only when they change, which prevents the computation from being repeated too many times.

    Memoizing Expensive API Responses:

    import React, { useMemo, useEffect, useState } from 'react';
    
      function ExampleComponent() {
        const [apiData, setApiData] = useState(null);
      
        useEffect(() => {
          // Make API request and set the response
          fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => setApiData(data));
        }, []);
      
        const processedData = useMemo(() => {
          if (!apiData) return null;
          // Perform data processing on apiData
          return apiData.map(item => item.name);
        }, [apiData]);
      
        return <div>Processed Data: {processedData ? processedData.join(', ') : 'Loading...'}</div>;
      } 

    As an example, the apiData state contains a response from an API. As a result, processedData is computed by mapping API response item names. Whenever the apiData dependency changes, the expensive data processing is performed.

    Memoizing Expensive Calculations:

    import React, { useMemo } from 'react';
    
      function ExampleComponent({ value1, value2 }) {
        const result = useMemo(() => {
          // Perform a computationally intensive calculation
          let sum = 0;
          for (let i = 1; i <= value1; i++) {
            sum += i;
          }
          return sum * value2;
        }, [value1, value2]);
      
        return <div>Result: {result}</div>;
      } 

    Based on value1 and value2, a computationally intensive calculation is performed to compute the result. Value1 and value2 are calculated only when the value changes.

    Caching Component Propagation:

    import React, { useMemo } from 'react';
    
      function ChildComponent({ expensiveProp }) {
        // Perform some expensive computation on the prop value
        const processedValue = useMemo(() => expensiveProp + 10, [expensiveProp]);
      
        return <div>Processed Value: {processedValue}</div>;
      }
      
      function ParentComponent() {
        const propValue = 5;
      
        return <ChildComponent expensiveProp={propValue} />;
      } 

    Taking the expensiveProp value from the ParentComponent, the processedValue in the ChildComponent is derived. The ChildComponent only re-renders the processed value when the expensiveProp value changes by memoizing the computation with useMemo.

    Optimizing Component Rendering:

    import React, { useMemo } from 'react';
    
      function ExampleComponent({ items }) {
        const itemCount = useMemo(() => items.length, [items]);
      
        return <div>Item Count: {itemCount}</div>;
      } 

    Based on the itemArray prop, this example computes the itemCount.