7
30

How to work with useCallback Hook in React

Reading Time: 2 minutes

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

What is useCallback Hook

Let’s imaging you need a function to updates itself when the function change. If the internal value is the same, you want the same function to return. In this kind of context, we can make use of a memory space to remember the function and return this function uncalled/unexecuted.

Do not mistaken useCallback hook with useEffect hook. useEffect hook runs whenever a state is updated ignoring the fact if anything in the function actually does not change.

Official useCallback documentation.

Using useCallback Hook

First of all, useCallback 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 function did not change, it will return the cached function.

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.

Here, in the ‘displayValueNicely’ function, the point to note is that the function does not change unless ‘displayValue’ is updating.

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

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

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

  const displayValueNicely = useCallback(
    (fruitCount) => {
      let backgroundColor = 'green';
      if (displayValue > 120) {
        backgroundColor = 'red';
      } 
      return (
        <div>
          <div style={background-color:${backgroundColor};}>
            {displayValue}
          </div>
          New Fruit Count: {fruitCount}
        </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>
  );
}

Conclusion

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

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

Show Comments

No Responses Yet

Leave a Reply