const Child = React.memo(({ count }) => { console.log('Child rendered'); return <div>{count}</div>; }); function Parent() { const [count, setCount] = React.useState(0); const [other, setOther] = React.useState(0); return ( <> <Child count={count} /> <button onClick={() => setOther(other + 1)}>Change Other</button> </> ); }
React.memo compares the previous and next props. If they are the same, it skips rendering the child component. Here, 'count' does not change when 'other' changes, so Child does not re-render.
function Counter() { const [count, setCount] = React.useState(0); const increment = React.useCallback(() => { setCount(count + 1); console.log('Count inside increment:', count); }, []); return <button onClick={increment}>Increment</button>; }
The increment function captures the initial value of 'count' (which is 0) because the dependency array is empty. It never updates, so it always logs 0 and sets count to 1 on every click.
const Child = React.memo(({ onClick }) => { console.log('Child rendered'); return <button onClick={onClick}>Click me</button>; }); function Parent() { const [count, setCount] = React.useState(0); return ( <> <Child onClick={() => setCount(count + 1)} /> <p>{count}</p> </> ); }
Each render creates a new arrow function for onClick, so React.memo detects a prop change and re-renders Child. To avoid this, use useCallback to memoize the function.
Option B correctly passes a function and dependency array. Option B never updates total after initial render. Option B passes a value instead of a function, causing error. Option B misses dependency array, so recomputes every render.
Option C combines React.memo to prevent re-renders when props don't change, and selective useContext with memoized values to avoid unnecessary updates. This is the most effective approach for deep trees.