DEV Community

Cover image for REACT APIS WITH EXAMPLE
PART1:React.memo()
keyvan
keyvan

Posted on • Updated on

REACT APIS WITH EXAMPLE PART1:React.memo()

introduction

A fast and reliable user interface (UI) is an important factor in modern web development. To improve performance React offers several APIs.

React.memo() is a high-order component that wraps around our functional component and returns a memoized version. whenever users interact with the UI React re-renders the component and compares the previous component to the next one.
if it is not the same then React would update the DOM with the new one (re-rendered component).

const MemoizedComponent=React.memo(Mycomponent)

Enter fullscreen mode Exit fullscreen mode

let's explore this API through an example. let's say we want to present a input wuth a heading or labels
whenever we change the input whole section get re-rendered(the heading or any other component) but in fact it's a unnecessary re-render

this is where React.memo() comes to the rescue!.it wraps around the Heading component and gives us a memoize result back.in simple terms, it gives us a rendered component and it will use the result on the next DOM update unless the component props have changed.
type something in the input. heading wrapped around memo is not re-rendering

areEqual

React.memo() accepts a second argument:


const memoizedComponent=React.memo(MyComponent,function areEqual(prevProps,newProps) 
        {
        // compare logic
        // return true of false
       })


Enter fullscreen mode Exit fullscreen mode

it passes prevProps and newProps to the function giving the ability to the developer to decide when to re-render the component.

💡 areEqual function must return true or false
returning true means no re-rendering returning false cause re-rendering

Remember React.memo() does a shallow comparison, it means if there are complex arrays or objects as props it always returns false, therefore, need to add a custom function(areEqual) to compare complex objects and arrays

when to use

whenever dealing with middle or big size components that consist of a couple of small size components and they keep re-rendering the same result over and over

when not to use

if the component updates occasionally and it wouldn't make much difference using a memoized version.

conclusion

although React does a lot of optimization internally but React.memo() gives the ability to the developer to define more suitable optimization. remember using React.memo() is not the solution to every performance issue. implementing a good design pattern and data structure is the key factor in optimization.

follow me on twitter😎

Top comments (0)