React Js UseCallback Hook Tutorial With Example

In this tutorial i will discuss about react hook useCallback. The react hook useCallback returns a memoized callback. Wrapping a component with React.Memo() signals the intent to reuse code. This does not automatically extend to functions passed as parameters.

Remember

  • useCallback returns a memoized version of a callback.

  • useCallback accepts as arguments a callback and a dependencies array.

  • The callback only changes if one of the dependencies has changed.

 

useCallback example

The following example will clear your concept of useCalback hook!

 

In the above example, the parent component, < Age / >, is updated (and re-rendered) whenever the Get older button is clicked.

And also consequently, the < Instructions / > child component is also re-rendered because the doSomething prop is passed a new callback with a new reference.

Point to be noted that even though the Instructions child component uses React.memo to optimize performance, it is still re-rendered.

So now how can this be fixed to prevent < Instructions / > from re-rendering needlessly?

useCallback with referenced function

 

 

Read also : React js useEffect Hook Tutorial with Example

 

Hope it can help you.

 

#react-js #react-hooks