I'm trying to understand how this React component works (it is meant to delay the rendering of its children):
function Delayed({ children, wait = 500 }) {
const [show, setShow] = React.useState(false);
React.useEffect(() => {
console.log("effect");
const timeout = window.setTimeout(() => {
console.log("setTimeout", show);
setShow(true);
}, wait);
return () => {
console.log("cleanup");
window.clearTimeout(timeout);
};
});
console.log("render", show);
return show === true ? children : null;
}
It produces an output like this:
1. render false
2. effect
3. setTimeout false
4. render true
5. cleanup
6. effect
7. setTimeout true
8. render true
I understand the order up until the very last line. Where does the last render log comes from? The boolean is already true at this point, so setState shouldn't trigger a re-render, but it does somehow. I'm guessing I'm missing something very obvious.
Codesandbox: https://codesandbox.io/s/fancy-fire-6t380