import React, { useState } from 'react'; const Child = React.memo(({ count }) => { console.log('Child rendered'); return <div>Count: {count}</div>; }); export default function Parent() { const [count, setCount] = useState(0); const [other, setOther] = useState(0); return ( <> <Child count={count} /> <button onClick={() => setOther(other + 1)}>Change Other</button> </> ); }
React.memo wraps the Child component to memoize it. It only re-renders if its props change. Since 'count' stays the same when 'other' changes, Child does not re-render, so 'Child rendered' logs only once.
The second argument to React.memo is a function that returns true if props are equal (to skip re-render) and false if props changed (to re-render). Option D returns true when user.id is the same, so it is correct.
import React, { useState } from 'react'; const Display = React.memo(({ value }) => { console.log('Display rendered with value:', value); return <div>{value}</div>; }); export default function App() { const [count, setCount] = useState(0); return ( <> <Display value={count} /> <button onClick={() => setCount(count)}>Click me</button> </> ); }
Clicking the button calls setCount with the same value (count). React.memo sees the same prop value and skips re-rendering Display, so the log appears only once on initial render.
import React, { useState } from 'react'; const Child = React.memo(({ data }) => { console.log('Child rendered'); return <div>{data.text}</div>; }); export default function Parent() { const [count, setCount] = useState(0); const data = { text: 'Hello' }; return ( <> <Child data={data} /> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }
Each render of Parent creates a new 'data' object. React.memo shallowly compares props by reference, so it sees a new object each time and re-renders Child.
React.memo performs a shallow comparison of props. It compares primitive values by value and objects by reference. If props are equal, it skips re-rendering the component.