← react hacks / react / avoid-re-renders-react-memo.md

Avoiding Unnecessary Re-renders with React.memo

Learn how to optimize your React applications by avoiding unnecessary re-renders using React.memo. This post includes examples and detailed explanations.

React.memo is a higher order component that helps prevent unnecessary re-renders. It does a shallow comparison of the previous and current props and re-renders the component only if the props have changed.

Here is an example of how to use React.memo:

const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});

In this example, MyComponent will only re-render if the props have changed. This can be highly beneficial for performance optimization, especially when dealing with larger components or lists.

However, it’s important to note that React.memo only does a shallow comparison, so it might not work as expected with complex objects or arrays. In such cases, you might need to implement a custom comparison function.

const MyComponent = React.memo(
  function MyComponent(props) {
    /* render using props */
  },
  (prevProps, nextProps) => {
    // return true if passing nextProps would return
    // the same result as passing prevProps, otherwise return false
  }
);

Remember, judicious use of React.memo can greatly enhance the performance of your React applications.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

  4. e28a5ca Building Seamless User Interfaces with React: A Step-by-Step Tutorial

    tag: reacttag: web-developmenttag: user-interface

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?