I have the following code (CodeSandbox):
function App() {
const [blah, setBlah] = useState(true);
console.log('BLAH', blah);
setBlah(true);
return <button onClick={() => setBlah(true)}>Blah</button>;
}
I understand that setBlah(true) at the top level of the component is causing too many re-renders. What I don't understand is if you comment out the top level setBlah(true) and start mashing the "Blah" button, why does the component not re-render? Both are setting the state of blah to true over and over, yet only the top level setBlah(true) causes a re-render.
From the React docs on Bailing out of a state update: "Note that React may still need to render that specific component again before bailing out." The key word here is "may", which to me means that my situation is valid according to the docs. So the question might become, under what conditions will calling setState, with the same value that is already set, cause a re-render? It would be useful to know this as one might want to put logic in front of their setState method to check if the value is the same as the current so as to not cause an erroneous re-render.