![]() |
VOOZH | about |
React.memo() is a higher-order component that optimizes functional components by preventing re-renders when props donβt change. It uses shallow comparison to reuse the previously rendered output, improving performance.
React.memo() stores previous props and compares them with new ones; if unchanged, it reuses the previous render and skips re-rendering.When incorporating React.memo(), it's crucial to exercise caution, as excessively memoizing components can lead to reduced performance by introducing unnecessary overhead. To optimize effectively, consider the following best practices:
React.memo() is easy to use and intuitive. Here's how to use React.memo() to memoize a functional component step-by-step:
Step 1: Import your React.memo() file at the top.
import React, { memo } from 'react';Step 2: To define your functional component using the below syntax.
const FunctionalComponet = ({ prop1, prop2 }) => {
return <div>{prop1} {prop2}</div>;
};
Step 3: To Memoize your component by wrapping it with React.memo():
const ToMemoized = memo(FuntionalComponent);Step 4: To use your memoized component in your parent component using the following syntax:
const ComponentParent = () => {
return (
<div>
<ToMemoized prop1="Hello" prop2="GeeksforGeeks" />
</div>
);
};
By applying React.memo() to your functional component, it is now memoized, ensuring that it will only re-render when there are changes in its props. The usage of memo is straightforward and simplifies the management of component rendering.
Example: In this example, `FuntionalComponent` is wrapped with `React.memo()`, which memoizes the component based on its props. If the `prop1` and `prop2` props remain the same between renders, React will reuse the previous render result, preventing unnecessary re-renders.
Output:
Strike a balance in optimizing and memoization efforts, avoiding unnecessary complexities while enhancing performance.