React Guess the Output
Advanced React behavior questions
Test your deep understanding of the React rendering engine.
Q1: State Batched Updates
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
};
return <button onClick={handleClick}>{count}</button>;
}- Answer: After one click, the count will be
1. (React batches these updates, andcountonly refers to the value from the current render).
Q2: Multiple State Effects
useEffect(() => {
console.log("A");
}, [count]);
useEffect(() => {
console.log("B");
}, []);- Answer: On mount, both
AandBfire. On update ofcount, onlyAfires.
Q3: Ref vs State
Changing a useRef's .current value does not trigger a re-render. Changing state always does.
Next Step: Prepare for Interview Q's.