Blog>
Snippets

Optimizing Sub Components with React.memo for Performance

Explores the use of React.memo to wrap sub components, preventing unnecessary re-renders when the data or props have not changed, thus improving performance in large datasets.
const MySubComponent = React.memo(function MySubComponent(props) {
  // This component will only re-render if props have changed.
  return <div>{props.value}</div>;
});
This code defines a sub component that utilizes React.memo for performance optimization. React.memo is a higher order component that prevents the component from re-rendering if its props have not changed, thereby improving performance especially in cases of large datasets or complex component trees.
function ParentComponent(props) {
  const [value, setValue] = React.useState('Initial Value');

  // Function to update state, triggering re-render
  const updateValue = () => setValue('Updated Value');

  return (
    <div>
      <MySubComponent value={value} />
      <button onClick={updateValue}>Update Value</button>
    </div>
  );
}
This ParentComponent demonstrates how to use the MySubComponent with React.memo. It includes a state 'value' that, when changed through the updateValue function, will pass new props to MySubComponent causing it to re-render only if the props ('value') have changed. This setup showcases the performance benefits of React.memo, as unnecessary re-renders of MySubComponent are avoided.