Setting the Same Value Doesn't Re-render
What you'll learn: Why calling setState with the same value your state already holds doesn't cause a re-render.
The Core Idea
React is smart about avoiding unnecessary work. When you call a state setter (like setCount) with a value that's identical to the current state value, React simply skips the re-render entirely. This is called a "bail out."
You've already learned that React compares old and new state to decide if a re-render is needed. Here's the natural consequence: if those values are the same, there's nothing new to display, so React does nothing.
function Counter() {
const [count, setCount] = useState(5);
const handleClick = () => {
setCount(5); // count is already 5
};
console.log('Component rendered');
return <button onClick={handleClick}>Count: {count}</button>;
}
Click the button as many times as you want—you'll only see 'Component rendered' logged once (on the initial render). Every subsequent click calls setCount(5), but since count is already 5, React bails out and doesn't re-render.
Why This Matters
This optimization happens automatically—you don't need to do anything special. It prevents wasted work when event handlers fire repeatedly with the same value, or when logic accidentally sets state to what it already is.
Think of it like a thermostat: if the room is already at 72°F and you set the thermostat to 72°F again, nothing happens. The system doesn't cycle the air conditioner for no reason.
Key Takeaway: Calling setState(currentValue) is a no-op—React detects the duplicate and skips the re-render entirely, making your app more efficient by default.