Performance: React.memo usage
React.memo affects how often a component re-renders, impacting interaction responsiveness and CPU usage.
const MyComponent = React.memo(function MyComponent(props) { return <div>{props.value}</div>; }); // Used with memo <MyComponent value={someValue} />
function MyComponent(props) { return <div>{props.value}</div>; } // Used directly without memo <MyComponent value={someValue} />
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without React.memo | Re-renders component every parent update | Triggers reflows if DOM changes | Higher paint cost due to frequent updates | [X] Bad |
| With React.memo | Skips re-render if props unchanged | No reflows if DOM unchanged | Lower paint cost by avoiding updates | [OK] Good |
What is the main purpose of React.memo in React?
Which of the following is the correct syntax to wrap a functional component MyComponent with React.memo?
Consider this code snippet:
const MyComponent = React.memo(({ count }) => {
console.log('Rendered');
return <div>Count: {count}</div>;
});
function App() {
const [count, setCount] = React.useState(0);
const [text, setText] = React.useState('');
return (
<>
<MyComponent count={count} />
<input value={text} onChange={e => setText(e.target.value)} />
</>
);
}What will be logged to the console when the user types in the input box?
count as prop.text state, causing App to re-render. However, the count prop remains unchanged (same primitive value), so React.memo skips re-rendering MyComponent.count does not change, React.memo prevents re-render, so 'Rendered' logs only once on mount.Consider this usage of React.memo:
const MyComponent = React.memo(({ value }) => {
return <div>Value: {value}</div>;
}, (prevProps, nextProps) => {
return prevProps.value === nextProps.value;
});Which of the following correctly describes this code?
prevProps.value === nextProps.value, which is correct to skip re-render when props are equal.You have a component wrapped with React.memo that receives a prop data which is an object. You notice it re-renders every time the parent renders, even if data has the same content. How can you fix this?
data -> Option BPass the test and this pattern moves unknown