How to use the useCallback hook for map rendering with React?

Sometimes, we want to use the useCallback hook for map rendering with React.

In this article, we’ll look at how to use the useCallback hook for map rendering with React.

How to use the useCallback hook for map rendering with React?

To use the useCallback hook for map rendering with React, we can pass in the function we want to update when a state or prop updates as the useCallback callback.

For instance, we write:

import React, { useCallback } from "react";

const ExpensiveComponent = ({ onEvent }) => {
  //...
  return <p>expensive</p>;
};

const MappedComponent = ({ id }) => {
  const onEvent = useCallback(() => console.log(id), []);
  return <ExpensiveComponent onEvent={onEvent} />;
};

const FrequentlyRerendersMap = ({ ids }) => {
  return ids.map((id) => {
    return <MappedComponent key={id} id={id} />;
  });
};

export default function App() {
  return <FrequentlyRerendersMap ids={[1, 2, 3]} />;
}

We have the ExpensiveComponent that takes the onEvent function prop.

Then we define the MappedComponent that defines the onEvent function which is defined with the useCallback hook with a callback.

Then callback is run when onEvent is called.

Next, we have the FrequentlyRerendersMap component that renders an array of MappedComponent with the ids.map method.

Finally, we render FrequentlyRerendersMap in App.

Conclusion

To use the useCallback hook for map rendering with React, we can pass in the function we want to update when a state or prop updates as the useCallback callback.