Unable to set state in the function of fullscreenchange event while exiting fullscreen

I want to toggle fullscreen mode by changing state when fullscreenchange event fires but state is not being changed when exiting fullscreen mode.

Here is the code:

import React, { useEffect, useState } from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { FullscreenExit, Fullscreen } from '@mui/icons-material';
import { Fab } from '@mui/material';
import Test1 from './components/Test1';
import Test2 from './components/Test2';

const App = () => {
  const [fullscreen, setFullscreen] = useState(false);

  useEffect(() => {
    document.addEventListener('fullscreenchange', onFullscreenChange, false);

    return () => {
      document.removeEventListener(
        'fullscreenchange',
        onFullscreenChange,
        false,
      );
    };
  }, []);

  const onFullscreenChange = () => {
    console.log('here!');
    setFullscreen(!fullscreen);
  };

  const openFullscreen = () => {
    const elem = document.documentElement;

    if (elem?.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem?.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    } else if (elem?.msRequestFullscreen) {
      elem.msRequestFullscreen();
    } else if (elem?.mozRequestFullScreen) {
      elem.msRequestFullscreen();
    }
  };

  function closeFullscreen() {
    if (document?.exitFullscreen) {
      document.exitFullscreen();
    } else if (document?.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document?.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document?.mozsExitFullscreen) {
      document.msExitFullscreen();
    }
  }

  return (
    <>
      <BrowserRouter>
        {console.log(fullscreen, 'fullscreen')}
        <Routes>
          <Route path='/' element={<Test1 />} />
          <Route path='/home' element={<Test2 />} />
        </Routes>
      </BrowserRouter>
      {!fullscreen ? (
        <Fab
          style={{
            position: 'fixed',
            bottom: '30px',
            right: '30px',
            backgroundColor: '#9e9e9e',
            opacity: '0.5',
          }}
          onClick={openFullscreen}>
          <Fullscreen style={{ color: '#183569' }} />
        </Fab>
      ) : (
        <Fab
          style={{
            position: 'fixed',
            bottom: '30px',
            right: '30px',
            backgroundColor: '#9e9e9e',
            opacity: '0.5',
          }}
          onClick={closeFullscreen}>
          <FullscreenExit style={{ color: '#183569' }} />
        </Fab>
      )}
    </>
  );
};

export default App;

Solution 1:

Try using this

setFullscreen(p => !p)