- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React Memo
- React.memo is a higher-order component (HOC) in React that memoizes functional components.
- It optimizes performance by preventing unnecessary re-renders when the component receives the same props.
Basic Usage
Applying React.memo to a functional component.
import React from 'react';
const MemoizedComponent = React.memo((props) => {
/* Component logic here */
});
export default MemoizedComponent;
Default Behavior
By default, React.memo performs a shallow comparison of props to determine whether to re-render.
import React from 'react';
const MemoizedComponent = React.memo((props) => {
/* Component logic here */
});
// Usage
const ParentComponent = () => {
const memoizedProps = { name: 'Darling' };
return <MemoizedComponent {...memoizedProps} />;
};
Custom Comparison Function
You can provide a custom comparison function for more control over the memoization process.
import React from 'react';
const MemoizedComponent = React.memo(
(props) => {
/* Component logic here */
},
(prevProps, nextProps) => {
/* Custom comparison logic */
return prevProps.id === nextProps.id;
}
);
// Usage
const ParentComponent = () => {
const memoizedProps = { id: 1, name: 'Darling' };
return <MemoizedComponent {...memoizedProps} />;
};
Use Cases for Memoization
Memoization is beneficial for optimizing pure functional components that solely depend on props.
import React from 'react';
const PureComponent = React.memo((props) => {
/* Pure functional component logic */
});
// Usage
const ParentComponent = () => {
const data = /* Some data */;
return <PureComponent data={data} />;
};
Avoiding Unnecessary Re-renders
Use React.memo to prevent re-renders when props don't change.
import React from 'react';
const ExpensiveComponent = ({ data }) => {
/* Expensive component logic using data */
};
const MemoizedExpensiveComponent = React.memo(ExpensiveComponent);
// Usage
const ParentComponent = () => {
const memoizedData = /* Some memoized data */;
return <MemoizedExpensiveComponent data={memoizedData} />;
};
Considerations
- Memoization is most effective for functional components that heavily rely on props.
- Avoid unnecessary memoization for components that have minimal re-renders or involve complex state logic.
Summary
Using React.memo is a powerful way to optimize React applications by selectively preventing re-renders of components. It is particularly useful for pure functional components that don't rely on local state and can be memoized based on props.