Memoization in React with Functional Components: Part 1

Use Case

A common use of memoization in React is preventing a child component from re-rendering when it does not need to. For example, if a parent component updates some state value that does not involve the child, by default React will re-render the child component. Using memoization however, we can restrict the re-rendering of child components to reduce unnecessary load.

The Problem

Below we have Table functional component with two separate states, count and buttonData. The button that changes the count state exists in the parent component, and that state is not passed to any of its children. For this reason, we do not want Button to re-render when count is changed, because they do not have anything to do together.

Lines 20–22 render a list of custom Button components
A console log is present to easily show when the component is rendered

The Solution

In order to prevent these costly and unnecessary re-renders, all we have to do is use memo on the Button component.

memo is imported from ‘react’

When You DO Want to Re-render

Assuming you only want to re-render the child component when its own state changes, all you have to do is update the state correctly. The example bellow will not re-render the child component.

There is a console log on line 6 to show when this table component renders
Spread operator on line 6

Keep In Mind

Memoizing a functional component only compares the props that are sent to the component to determine rendering. If the Button component itself has state or context, utilizing the useState, useReducer, or useContext hooks then it will render as expected.

  1. https://reactjs.org/docs/react-api.html#reactmemo
  2. https://www.freecodecamp.org/news/memoization-in-javascript-and-react/#:~:text=In%20programming%2C%20memoization%20is%20an,instead%20of%20computing%20it%20again.
  3. https://blog.openreplay.com/improving-react-application-performance-react-memo-vs-usememo/#:~:text=memo%20utilizes%20shallow%20comparison%20by,the%20worse%20the%20overhead%20is.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aidan McBride

Aidan McBride

43 Followers

I am a Front End Engineer and graduate of Flat Iron coding bootcamp. Currently I work in the regulatory industry using React.