Concept Flow - React.memo usage
Component receives props
React.memo compares new props
Skip re-render
Update DOM if needed
React.memo checks if props changed. If not, it skips re-render to save work.
const MyComponent = React.memo(({ count }) => { console.log('Rendered:', count); return <div>{count}</div>; }); <MyComponent count={1} /> <MyComponent count={1} /> <MyComponent count={2} />
| Step | Props Received | Props Compared | Render Occurs? | Console Output |
|---|---|---|---|---|
| 1 | { count: 1 } | No previous props | Yes | Rendered: 1 |
| 2 | { count: 1 } | Compare with { count: 1 } | No | |
| 3 | { count: 2 } | Compare with { count: 1 } | Yes | Rendered: 2 |
| Variable | Start | After 1 | After 2 | After 3 |
|---|---|---|---|---|
| props.count | undefined | 1 | 1 | 2 |
| rendered | false | true | false | true |
React.memo is a function that wraps a component. It compares new props with previous props. If props are equal, it skips re-rendering. This improves performance by avoiding unnecessary updates. Use it for functional components that render the same output for same props.
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