Consider this React component that uses useCallback. What will be logged when the button is clicked twice?
import React, { useState, useCallback } from 'react'; function Counter() { const [count, setCount] = useState(0); const increment = useCallback(() => { console.log('Count before increment:', count); setCount(count + 1); }, []); return ( <button onClick={increment}>Increment</button> ); } export default Counter;
Remember that useCallback with an empty dependency array keeps the same function instance and closes over the initial count value.
The increment function is created once with useCallback and an empty dependency array. It captures the initial count value (0). So every time it runs, it logs 0 before incrementing. The state updates, but the function does not see the updated count.
Given this React component, what will be the value of count after clicking the button two times?
import React, { useState, useCallback } from 'react'; function Counter() { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount(prev => prev + 1); }, []); return ( <button onClick={increment}>Increment</button> ); } export default Counter;
Look at how setCount uses a function to update state.
The increment function uses the functional form of setCount, which always updates based on the latest state. So clicking twice increments count from 0 to 2.
Which code snippet correctly memoizes handleClick so it updates when propValue changes?
Think about which dependencies should be included to update the callback when props change.
Option D correctly includes propValue in the dependency array, so the callback updates when propValue changes. Option D never updates, C has no dependency array (runs every render, so no memoization), and D depends on a setter which is stable and unrelated.
Examine this code. Why does the handleClick function always log the initial value of count?
import React, { useState, useCallback } from 'react'; function Counter() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log(count); }, []); return ( <> <button onClick={() => setCount(count + 1)}>Increase</button> <button onClick={handleClick}>Log Count</button> </> ); } export default Counter;
Think about how dependency arrays affect closures in hooks.
The empty dependency array means the callback is created once and closes over the initial count value. It never sees updates, so it always logs the initial count.
Choose the best explanation for why and when to use useCallback in React components.
Think about how React compares props and why function identity matters.
useCallback returns a memoized function that keeps the same reference unless dependencies change. This helps prevent child components from re-rendering unnecessarily when passed functions as props.