1

I have react code that works like so:

  const [screenStream, setScreenStream] = useState(null);

  useEffect(() => {
    getPermissionsAndStreams();
  }, []);

  const getPermissionsAndStreams = () => {
    getDisplayStream()
      .then((_screenStream) => {
        // After permission given
        setScreenStream(_screenStream);
        ...
      });
  };

I.e. when the component loads, it requests permission from the user and saves that to the setStream variable.

However, this does not work when react's StrictMode is turned on. It seems to have a race condition where the page reloads, resetting screenStream to null, after setScreenStream has been activated.

Is there a different pattern of code that would avoid this problem? Or do we have to turn off strict mode?

Will Taylor
  • 1,994
  • 2
  • 23
  • 36

1 Answers1

1

It's really weird that the value came back to null after set it to another value, useState hook receive null only the first execution then it is managed by setScreenStream, the only way to go back to null is setting that intentionally

Could be that the service is failing by any chance or there is another setScreenStream affecting your development

Also check the position of const getPermissionsAndStreams try tu put it above the useEffect, remember that with const, hoisting is not working as you could expect

Yuu
  • 337
  • 1
  • 4
  • Also check the position of const getPermissionsAndStreams try tu put it above the useEffect, remember that with const, hoisting is not working as you could expect (added to the main answer) – Yuu Jun 15 '23 at 19:00