Controlling your stateless React components

This is a very short summary of React.memo that was introduced in React 16.6 in Oct 2018 and can be used as a wrapper around stateless functional components.

Some examples demonstrating stateless functional components are below:

import React from 'react';

//nameless default functional component 
export default (props) => {
  return 
      <button disabled={props.buttonDisabled}>{props.text}</button>
}

//named functional component
export const BasicButton = (props) => {
  return 
      <button disabled={props.buttonDisabled}>{props.text}</button>
}

React.memo takes advantage of in memory caching, recording the output for a component given a specific set in inputs. If the inputs remain unchanged, the function will return the cached result rather than recalculate.

In the above examples React.memo can be added to check whether the props passed into the functional button component are different to the memoized props parameter. This below code snippet shows only when the buttonDisabled property changes in some container where the property is defined that the component will then re-render.

export const BasicButton = React.memo(props => {
  /* only rerenders if props change */
  return 
      <button disabled={props.buttonDisabled}>{props.text}</button>
});

//wrapping an existing component also using implicit return
const BasicButton = props => <button disabled={props.buttonDisabled}>{props.text}</button>

export const MemoizedBasicButton = React.memo(BasicButton);

Adding React.memo to your app’s functional components is a very simple way to improve the performance of the app as re-rendering will only occur when their props change.

Leave a comment