This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Are you using useCallback properly 🤔


I did not up till not too long ago.
On the venture my crew is engaged on we had been use useCallback for each operate prop handed to the kid elements.
This strategy would not offer you advantages as you could count on.

Our code seemed like this (not actually 😀)

const ParentComponent = () => {
  ...
  const onClick = useCallback(() => console.log('click on'), [])  

  return <ChildComponent onClick={onClick} />
}

const ChildComponent = ({ onClick }) => {
  return <button onClick={onClick}>Click on me</button>
}
Enter fullscreen mode

Exit fullscreen mode

Method with out useCallback

const ParentComponent = () => {
  ...
  return <ChildComponent onClick={() => console.log('click on')} />
}
Enter fullscreen mode

Exit fullscreen mode

The advantages of the primary strategy in comparison with the second are minimal and in some circumstances contemplating the price of useCallback the second strategy is quicker.

The factor is creating and destroying features on every rerender shouldn’t be an costly operation as you could assume and changing that with useCallback would not convey a lot advantages.

Another excuse why we all the time used the useCallback hook is to forestall the kid element rerender if its props did not change however this was incorrect as a result of at any time when the mum or dad element rerenders the kid element will rerender as properly nonetheless the kid props are modified or not.



React.memo

If you wish to rerender the kid element solely when its props or state modified you need to use React.memo.
You’ll be able to obtain the identical with PureComponent or shouldComponentUpdate if you’re working with class elements as a substitute of practical.

If we wrap ChildComponent from our first instance with React.memo

const ChildComponent = React.memo(({ onClick }) => {
  return <button onClick={onClick}>Click on me</button>
})
Enter fullscreen mode

Exit fullscreen mode

when the ParentComponent rerenders and props of the ChildComponent do not change, the ChildComponent won’t rerender.

This provides us a very good perception once we ought to use useCallback hook.
useCallback ought to be utilized in mixture with the React.memo.

I can’t say that ought to be all the time the case, you need to use useCallback with out React.memo in the event you discover it helpful however most often, these two ought to be the pair. ❤



When to make use of React.memo

There aren’t any clear directions on when to do it, somebody thinks it’s best to use it all the time and I am for the strategy “measure efficiency of your element and optimize it with React.memo if wanted”.

The elements which you’ll wrap with React.memo by default are these with a variety of youngsters like tables or lists.

Now we’ll check out an instance.
You’ll be able to clone it and take a look at it by your self from right here https://gitlab.com/markoarsenal/use-callback.

It appears to be like like this (very artistic 😀)

Image description

We have now an extended record of feedback (a very good candidate for React.memo) and now we have the counter button on the highest whose predominant objective is to set off the rerender.

The code appears to be like like this

const House = () => {
  const [counter, setCounter] = useState(0);
  const onClick = useCallback(() => console.log("click on"), []);

  return (
    <Profiler
      id="House web page"
      onRender={(compName, mode, actualTime, baseTime) =>
        console.log(compName, mode, actualTime, baseTime)
      }
    >
      <predominant className="max-w-5xl p-8 m-auto">
        <div className="flex justify-center mb-8">
          <button
            onClick={() => setCounter(counter + 1)}
            className="px-3 py-1 border border-gray-500"
          >
            Replace {counter}
          </button>
        </div>
        <Feedback feedback={feedback} onClick={onClick} />
      </predominant>
    </Profiler>
  );
};
Enter fullscreen mode

Exit fullscreen mode

You’ll be able to discover Profiler element as a root element, it is this one https://reactjs.org/docs/profiler.html.
We’re utilizing it to measure rendering instances.
You’ll be able to discover onRender callback, we’re logging a few issues inside however crucial are actualTime and baseTime. The actualTime is the time wanted for element rerender and baseTime is the time to rerender element with none optimizations. So if you haven’t any optimizations inside your element actualTime and baseTime ought to be equal.

Feedback element appears to be like like this (discover that’s wrapped with React.memo)

const Feedback = ({ feedback, onClick }: CommentsProps) => {
  return (
    <part>
      {feedback.map((remark) => {
        return (
          <Remark
            {...remark}
            className="mb-4"
            onClick={onClick}
            key={remark.id}
          />
        );
      })}
    </part>
  );
};

export default memo(Feedback);
Enter fullscreen mode

Exit fullscreen mode

Now I’ll run our instance with 500 feedback in Chrome, hit the “Replace” button just a few instances to trigger rerender and submit outcomes right here.

Image description

So, on each rerender we’re saving round 30ms which is appreciable.

Let’s strive another factor, as a substitute of the record of the feedback to render one, memoized remark and see what measurements are.

{/* <Feedback feedback={feedback} onClick={onClick} /> */}
<Remark {...feedback[0]} onClick={onClick} />
Enter fullscreen mode

Exit fullscreen mode

Image description

Nonetheless, now we have time financial savings however they’re neglecting which implies that React doesn’t have bother rerendering these small and easy elements, and memoizing these would not have a lot sense.
Alternatively memoizing element that comprises a variety of youngsters is one thing you possibly can profit from.

Hope you loved studying the article and that now you may have a greater overview of useCallback and React.memo and when to make use of them.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?