简体   繁体   中英

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

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
}

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM