November 18, 2022

React.memo With Examples

When we create an application, we would definitely want it to be well optimized and performing fast. React.memo is one such performance optimization technique provided in React.


What is React.memo

In React, when a component re-renders, React re-renders all of its children recursively even if child component has no changes. What if you could check if child component has any changes and re-render it only if there are changes otherwise use the cached version of child component when parent component re-renders.

That's what React.memo does, with memo, you can create a component that React will not re-render when its parent re-renders as long as its new props are the same as the old props. Such a component is said to be memoized.

How to use React.memo

Syntax of memo is as given below-

const MemoizedComponent = memo(SomeComponent, arePropsEqual?)

To memoize a component, wrap the component in a call to memo. It returns a memoized version of the wrapped component to speed up the render process.

React.memo only checks for prop changes. By default, it will only shallowly compare complex objects in the props object. Which means it will only check for value equality not for reference equality. Passing one or more references types as a prop will break the memoization and cause the component to re-render.

You can also provide a custom comparison function, which React then uses to compare the old and new props instead of using shallow equality. This function is passed as a second argument to memo. It should return true only if the new props would result in the same output as the old props; otherwise, it should return false.

React.memo example

In the example there is a parent component MovieLikes which shows the likes count and delegates the rendering of the movie information to the Movie Component.

MovieLikes.js

import Movie from "./Movie";

const MovieLikes = (props) => {
    console.log('Rendering MovieLikes Component')
    return(
    <div>
        <Movie title={props.title} genre={props.genre} />
        <span>Likes: {props.likeCount}</span>
    </div>
    );
}
export default MovieLikes;

Movie.js

import React from "react";
const Movie = (props) => {
    console.log('Rendering Movie Component')
    return(
    <div>
        <p>Title: {props.title}</p>
        <p>Genre: {props.genre}</p>
    </div>
    );
}
export default Movie;

App.js

function App() {  
  const [likeCount, setLikeCount] = useState(0);
  function incrementLikeCount() {
    setLikeCount(likeCount + 1);
  }
  return (
    <div>
      <MovieLikes title="The Conjuring" genre="horror" likeCount={likeCount} />
      <button onClick={incrementLikeCount}>Like</button>
    </div>
  );
}
export default App;

Here we have a 'Like' button, clicking it results in state change and as a consequence component re-rendering happens.

memo in React

As you can see log placed in the Movie component is also displayed every time meaning Movie component is also rendered with each state change even though props to Movie component does not change.

Movie component can be wrapped inside a memo to prevent this unwanted re-rendering of the Movie component and saving the time spent in the re-rendering of this component.

Here is the changed Movie component. Note that React.memo is used with the export.

import React from "react";
const Movie = (props) => {
    console.log('Rendering Movie Component')
    return(
    <div>
        <p>Title: {props.title}</p>
        <p>Genre: {props.genre}</p>
    </div>
    );
}
export default React.memo(Movie);

With that change now you can see that the Movie component is not re-render whenever Like button is clicked.

React.memo example

Important points about React.memo

  1. React.memo is a higher order component. A higher-order component is a function that takes a component and returns a new component.
  2. Use React.memo with functional components not with class components.
  3. React.memo only checks for prop changes. If the props passed down to the component doesn't change you will get the memoized component. If the props change then the component is re-rendered.
  4. If your function component wrapped in React.memo has a useState, useReducer or useContext Hook in its implementation (something other than props), it will still re-render when state or context change.
  5. Use memo with components that render quite often.
  6. You will have to ensure that the time spent in re-rendering of the component is more than the time consumed in the comparison of props (old and new props) then only you will have performance gain otherwise memo may increase the total rendering time.

React.memo Vs useMemo()

Since React.memo and useMemo hook both are used for memoization in React so it is important to know what is the difference between them.

React.memo is a higher-order component whereas useMemo is a react hook. React.memo caches the whole component and returns the component during re-renders. useMemo caches the computed value and returns that during re-renders.

That's all for the topic React.memo With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment