Consider this React component that updates state on button clicks.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
}
return (
<button onClick={handleClick}>Count: {count}</button>
);
}What will the button display after clicking it twice?
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 1); } return ( <button onClick={handleClick}>Count: {count}</button> ); }
Remember that React batches state updates and the count variable does not update immediately inside the same function call.
Both setCount(count + 1) calls use the same count value because state updates are asynchronous and batched. So the count increases by 1 per click, not 2.
How can you update React state twice in one event handler so that the state increments by 2?
const [count, setCount] = useState(0);
function handleClick() {
// update state twice here
}const [count, setCount] = useState(0); function handleClick() { // update state twice here }
Use the updater function form of setCount to get the latest state value.
Using setCount(prev => prev + 1) twice correctly increments the state twice because each updater receives the latest state value.
Look at this React component:
function Example() {
const [text, setText] = useState('');
function handleChange(e) {
setText(e.target.value);
console.log(text);
}
return <input value={text} onChange={handleChange} />;
}Why does console.log(text) always log the previous value, not the current input?
function Example() { const [text, setText] = useState(''); function handleChange(e) { setText(e.target.value); console.log(text); } return <input value={text} onChange={handleChange} />; }
Think about when React updates state and when the console.log runs.
React state updates do not happen immediately. The text variable inside the handler still holds the old value when console.log runs.
Given this React state:
const [user, setUser] = useState({ name: 'Alice', address: { city: 'NY' } });Which option correctly updates the city to 'LA' without mutating the original state?
const [user, setUser] = useState({ name: 'Alice', address: { city: 'NY' } });
Remember to create new objects for nested state to avoid mutation.
Option A creates a new user object and a new address object with the updated city, preserving immutability.
Options B and D mutate the existing state object, which is bad practice and can cause bugs.
Option A replaces the whole user object but hardcodes the name, which is less flexible.
In React, if you call setState (or setCount) with the same value as the current state, what will React do?
Think about React's optimization to avoid unnecessary work.
React compares the new state with the current state using Object.is. If they are the same, React skips re-rendering to improve performance.