memo in React
Expert-Level Explanation
React.memo
is a higher-order component that memoizes a functional component. It performs a shallow comparison of the previous and new props and re-renders the component only if the props have changed. This is similar to PureComponent
but is used for functional components instead of class components. React.memo
is useful for optimising performance, particularly in components that render frequently or have expensive rendering.
Creative Explanation
Think of React.memo
as a painter who keeps a copy of his last painting (the previous props). When asked to paint again (component re-renders), he first checks if the new scene (new props) is different from his last painting. If it's the same, he simply displays the old painting instead of making a new one, saving time and effort.
Practical Explanation with Code
Using React.memo
in a functional component:
import React, { memo } from 'react';
const MyComponent = memo(function MyComponent(props) {
return <div>{props.message}</div>;
});
In this code, MyComponent
will only re-render if props.message
changes.
Real-World Example
In a social media feed, individual Post
components could be wrapped inReact.memo
. This optimisation means a Post
only re-renders when its content or associated data (like likes or comments) changes, improving performance as users scroll through the feed.