Updating React state in nested setTimeout callbacks

Can someone please tell me what’s wrong with this and why the state of the ‘video variable’ remains false? So, even after the h2 element has rendered and is visible (i.e. the state of the video variable has been updated to true), when I click and call the hideVideo function, the video state remains false? Many thanks.

export default function App() {
  const [message, showMessage] = useState(false);
  const [video, setVideo] = useState(false);
  
let modalTimeout, videoTimeout;

  useEffect(() => {
   
    window.addEventListener("click", hideVideo);
    setupTimeouts();
    return () => {
      clearTimeout(modalTimeout);
      clearTimeout(videoTimeout);
    };
  }, []);

  const setupTimeouts = () => {
    modalTimeout = setTimeout(() => {
      showMessage(true);

      videoTimeout = setTimeout(() => {
       
        showMessage(false);
        setVideo(true);
      }, 4000);
    }, 2000);
  };

  const hideVideo = () => {
    console.log(video);
    showMessage(false);
    if (video === true) {
      setVideo(false);
      
    }
  };

  return (
    <div className="App">
      {message && <h1>Message</h1>}
      {video && <h2>Video</h2>}
    </div>
  );
}

Answer

When you call useEffect the window listener attach the default video value that is false to the function hideVideo() so it will be always false, I created a button to show you that the video state value does change. check the last test function

export default function App() {
const [message, showMessage] = useState(false);
const [video, setVideo] = useState(false);
let modalTimeout, videoTimeout;

useEffect(() => {
  window.addEventListener("click", hideVideo);
  setupTimeouts();
  return () => {
    clearTimeout(modalTimeout);
    clearTimeout(videoTimeout);
  };
  }, []);

const setupTimeouts = () => {
  modalTimeout = setTimeout(() => {
    showMessage(true);
    videoTimeout = setTimeout(() => {
      showMessage(false);
      setVideo(true);
    }, 4000);
  }, 2000);
};

const hideVideo = () => {
  console.log(video);
  showMessage(false);
  if (video) {
    setVideo(false);
  }
};
const test = (event) => {
  event.stopPropagation();
  console.log(video)
}
return (
  <>
    {message && <h1>Message</h1>}
    {video && <h2>Video</h2>}
    <button onClick={test}>test</button>
  </>
);

}