Member-only story
React Performance: How to avoid redundant re-renders
Redundant re-renders are a common issue in React. If not taken seriously, this issue can quickly worsen the performance of your application.
By understanding and implementing these practices, you can avoid the problem and keep your rendering process running smoothly.
memo and useCallback
Let’s first cover the main toolkit under your belt for cutting down the re-renders: memo
and useCallback
. You should know how these utility functions work in order to be able to optimize React performance.
memo is a utility method that React library provides to memoize the state of the components and make it so that they only render when their props change. All you need to do is wrap your components declaration with the function:
Now, the ListItem
component will no longer re-render when its parent does. The only time the ListItem
would re-render is if the props passed to it change. This is especially useful when working with large lists. List items will not re-render each time the state of the parent list changes. This tweak could drastically improve the performance of your UI.
So what about useCallback? In the previous example, our ListItem
did not receive any event handler props. Yet passing event handlers from parent to child is a common pattern that you will, no doubt, use a lot when working with React.
There is, however, a slight problem with passing event handlers to memoized components. Event handlers are usually declared inside of the parent component, which means they will re-render each time the parent component does. This will make wrapping our child components with memo
useless since the event handler prop will cause it re-render each time anyway.
And that’s where useCallback
comes in. This utility method returns a memoized version of any callback function it receives. The only time it would recalculate the value of the function you pass is if any of the dependencies you provided change.