React.memo()
React.memo
is a higher order component. It’s similar to React.PureComponent
but for function components instead of classes.
If your function component renders the same result given the same props, you can wrap it in a call to React.memo
for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.
For Example, have a look at the below code
We have created a functional component to show a value which is received through props
We are setting the state with initial value as 1 and in componentDidMount
we are updating the state with the same value for every 1000ms. and then the state value is passed as a prop to the functional component.
Now when we run the app and see the developer console by pressing ctrl + shift + i
you can see the value gets updated for every 1000 ms
What happens is whenever the state gets updated the page gets re-rendered again.
How can we fix it?
Well if we have used Class component we can simply extend the component to PureComponent. But we are using functional component so we have to use React.memo
Have a look at the updated functionalComp.js
We have added the memo and if you run the application you can see the value has been called only once and not multiple times. But if you call the value randomly in setState then for every change the page gets re-rendered.
By default React.memo() will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.
If you run the above code you will see theareEqual()
is called each time whenever the props get changed and if we return true it won’t render the component else it will render the component like below
This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.
Unlike the
shouldComponentUpdate()
method on class components, theareEqual
function returnstrue
if the props are equal andfalse
if the props are not equal. This is the inverse fromshouldComponentUpdate
.
Author: Nidhinkumar