Home > Enterprise >  How to wait for state while setting consecutive states in react using UseState Hook
How to wait for state while setting consecutive states in react using UseState Hook

Time:09-22

I am calling a function to handle the video play on click and there I want to set consecutive states using useState hook. But I want to wait for first one before cursor goes to next setState(useState Hook) without using useEffect hook to monitor it. This is a function just as an example.

const videoPlayHandler = () => {

     setIsPaused(true); //wait for this one 
     setIsPlay(false);  //run just after first state is done
}

CodePudding user response:

In react 18, you can force it to do a synchronous rerender by using flushSync:

import { flushSync } from 'react-dom';

const videoPlayHandler = () => {
  flushSync(() => {
    setIsPaused(true);
  });  
  setIsPlay(false);
}

I recommend reading the notes section on react's flushSync documentation

Note:

flushSync can significantly hurt performance. Use sparingly.

flushSync may force pending Suspense boundaries to show their fallback state.

flushSync may also run pending effects and synchronously apply any updates they contain before returning.

flushSync may also flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.

CodePudding user response:

This doesn't answer your question, but in your case it would make more sense to just keep 1 state variable that determines if the video is playing or not.

const [isPlaying, setIsPlaying] = useState(false);

const videoPlayHandler = () => {
  setIsPlaying(true);
}

const videoPauseHandler = () => {
  setIsPlaying(false);
}
  • Related