React.memo() & useCallback hook in React

Before understand useCallbcak we will also discuss React.memo()

useCallback() and React.memo() both we can use for improving the React application and prevent extra rendering of components.

Let’s understand the problem first with the below example. One parent component may have so many child component and passing props to each child as well.



Run the above code and open developer console

When you click any button it render all four components. In Real world application we will have so many components and if all render with one state value change then it may create performance problem

So React.memo() function can help you to render the components only when respective props get change.

For Example if we click on “increment age” button then only DisplayValue with age props will render and when “increment salary” button is clicked then only DisplayValue with salary props will render.

We only need to wrap the component with React.memo() function before export as given below

Another problem if you notice when we click on “Increment Age” button event handling function reference pass to <IncrementButton> and this component we use for Incrementing Age as well as Incrementing Salary.

If you wrap IncrementButton Component with React.memo() then also it render for each event.

To prevent this rendering useCallback hook can help you to prevent unnecessary rendering while passing such kind of function reference from parent to child component

Here you can see incrementAge and incrementSalary function we have wrap with useCallback() hook and also set the dependency with second argument respectively.

Related Posts

Leave a Reply