Consider this React component that uses useMemo to optimize a calculation. What will be displayed when the button is clicked twice?
import React, { useState, useMemo } from 'react'; function Counter() { const [count, setCount] = useState(0); const double = useMemo(() => { console.log('Calculating double'); return count * 2; }, [count]); return ( <div> <p>Count: {count}</p> <p>Double: {double}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
Think about when useMemo recalculates the value based on dependencies.
useMemo recalculates the value only when count changes. The console log appears once per change, so clicking the button twice triggers two recalculations, but each render only logs once. This optimizes performance by avoiding unnecessary recalculations.
result after this code runs?Given this React snippet using useMemo, what will result be after the component renders?
import React, { useState, useMemo } from 'react'; function Example() { const [num, setNum] = useState(5); const result = useMemo(() => num * 3, []); return <div>{result}</div>; } export default Example;
Look at the dependency array and initial state value.
The useMemo runs once on mount because the dependency array is empty. It uses the initial num value 5, so result is 15.
Choose the correct syntax to memoize the result of computeValue() based on input.
Remember that useMemo expects a function as the first argument.
Option D correctly passes a function that calls computeValue(input). Option D calls the function immediately, Option D returns the function itself, and Option D has wrong arguments.
count changes?Look at this code snippet. Why does memoizedValue not update when count changes?
const memoizedValue = useMemo(() => count * 2, []);
Check the dependency array carefully.
An empty dependency array means the memoized value is calculated only once on mount. To update when count changes, it must be included in the dependency array.
Choose the best explanation for why developers use useMemo in React.
Think about performance optimization and when calculations run.
useMemo caches the result of a calculation and only recalculates when dependencies change, improving performance by avoiding unnecessary work.