Execution order of useEffect in combination with updating state

Viewed 49

Given the following simple component:

const MyComponent = () => {
  const [state, setState] = useState("");

  useEffect(function a() {
    // Do stuff
    setState("Some value");
  }, [])

  useEffect(function b() {
    // Do stuff
  }, [state]);

  // return some fancy JSX
}

The execution order will be:

  1. MyComponent mounts and MyComponent() executes and returns JSX.
  2. function a is executed and the state change gets queued.
  3. function b is executed (The state change from 2) is not yet reflected, so state === "").

Now my question is, given that state might change by other triggers than drafted here, is there any guarantee that the setState("Some value") from function a will have happened by the time the effect b is executed the next time (after step 3) above)?

In other words, may there be any constellation where b will be called because state has changed, but the setState("Some value") from a has not happened yet?

1 Answers

Yes it's very possible. Here's the demo:

function Home() {

  const [state, setState] = useState("");

  useEffect(function a() {
    // Do stuff
    setTimeout(() => {
      setState("Some value");
    }, 10000);

  }, [])

  useEffect(function b() {
    // Do stuff
  }, [state]);

  // return some fancy JSX
  return <>
    <button onClick={() => setState('this is executed first')}>

      hello

    </button>

    <h1>{state}</h1>
  </>

}

The state will update as soon as you clicked the button and then changed again after 10 seconds (from function A)

Related