5
28

How to work with useMemo Hook in React

Reading Time: 2 minutes

React hooks are very useful functions provided in React functional component and one of them is useMemo hook. We have also covered other hooks like useEffect, useContext.

What is useMemo Hook

Let’s imaging you need a heavy-duty function to only run when a state value change. If the state value is the same, you want a cache result to return. In this kind of context, we can make use of a memory space to remember the previous response and return the result.

Do not mistaken useMemo hook with useEffect hook. useEffect hook runs whenever a state is updated ignoring the fact if the value actually does not change.

Official useMemo documentation.

Using useMemo Hook

First of all, useMemo function takes in 2 argument. One is a callback function and the other is an array of dependencies. Once any of the dependencies is having a different value, the callback function will be executed. If the dependencies have the same value, it will return the cached result computed in the previous run.

We will take an example where we want to allow user to optionally update the display only when the button is trigger. Let’s assume that it is a very complex and time consuming logic although the one in the example is a simple logic.

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

const fruitComponent = () => {
  const [fruitCount, setFruitCount] = useState(100);
  const [ displayValue, setDisplayValue ] = useState(100);

  const increment = () => {
    setFruitCount(fruitCount + 1);
  };

  const displayValueNicely = useMemo(
    () => {
      let backgroundColor = 'green';
      if (displayValue > 120) {
        backgroundColor = 'red';
      } 
      return (
        <div style={background-color:${backgroundColor};}>
          {displayValue}
        </div>
      );
    }, [displayValue]
  );

  return (
    <Fragment>
      <span>Number of fruits: {fruitCount}</span>
      <button onClick={() => increment()}> + </button>
       <button type='button' onClick={() => setDisplayValue(fruitCount)}>
         Update Value
       </button>
       {displayValueNicely}
    </Fragment>
  );
}

Be careful that in the official documentation, react have mention that we may use useMemo hook to optimise performance, but it does not guarantee the it always works. This is because their implementation may choose to forget some values.

Conclusion

The usage of useMemo may be good if the function to execute is very time consuming and skip when there is no change in value. However, there is also an additional step where useMemo hook will compare the old value with the new value.

Thus, it is a good practice to always compare before making the decision to use useEffect hook or useMemo hook.

Show Comments

No Responses Yet

Leave a Reply