Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useCallback hook for map rendering

When passing callback to component, I should use useCallback hook to return a memoized callback (to prevent unneeded renders):

import doSomething from "./doSomething";
const FrequentlyRerenders = ({ id }) => {
  const onEvent = useCallback(() => doSomething(id), [id]);
  return (
    <ExpensiveComponent onEvent={ onEvent } />
  );
};

But what if I am using map? for example:

import doSomething from "./doSomething";
const FrequentlyRerendersMap = ({ ids }) => {
  return ids.map(id => {
    const onEvent = useCallback(() => doSomething(id), [id]);
    return (
      <ExpensiveComponent key={id} onEvent={ onEvent } />
    );
  });
};

How should I properly use useCallback? Is the above the right way to pass multiple callbacks? Is it really works and know to memioze every callback according to an item of an array?

like image 246
Naor Avatar asked May 03 '19 05:05

Naor


People also ask

When would you use a useCallback hook?

The useCallback hook is used when you have a component in which the child is rerendering again and again without need. Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

Does useCallback re render?

The key takeaway here is that useCallback returns you a new version of your function only when its dependencies change, saving your child components from automatically re-rendering every time the parent renders.

Why we use useCallback hook in react?

The React useCallback Hook returns a memoized callback function. Think of memoization as caching a value so that it does not need to be recalculated. This allows us to isolate resource intensive functions so that they will not automatically run on every render.

Can I use useCallback in useEffect?

Hence, inside the List component, useEffect hook calls the setItems and prints “Fetching items” as its dependency has changed. The solution to the above problem: Here we can use the useCallback function to memoise the getItems() function depending upon the input number.


Video Answer


1 Answers

Convert the returned mapped JSX into a component and then you can useCallback without problems

import doSomething from "./doSomething";
const MappedComponent =(props) => {
   const onEvent = useCallback(() => doSomething(props.id), []);
   return (
      <ExpensiveComponent onEvent={ onEvent } />
   );
}

const FrequentlyRerendersMap = ({ ids }) => {
  return ids.map(id => {
    return <MappedComponent key={id} id={id} />
  });
};
like image 189
Shubham Khatri Avatar answered Oct 10 '22 06:10

Shubham Khatri