3

When using multiple useEffect is there and order in which they are called?

Consider the following code

import React from "react";

export default function App() {
  const [x, setX] = React.useState(2);

  React.useEffect(() => {
    console.log("A");
    setX(1);
  }, []);
  React.useEffect(() => {
    console.log("B");
    console.log(x);
  }, []);

  return (
    <div className="App">
      <h1>Hello {x}</h1>
    </div>
  );
}

The Console output is

A
B
2

Why x is 2 and not 1?

2 Answers2

0

Initial useEffect are called in the order they appear in your code. For example:

useEffect(() => {
    console.log('useEffect-1')
}, [])
useEffect(() => {
    console.log('useEffect-2')
}, [])
useEffect(() => {
    console.log('useEffect-3')
}, [])

Output:

useEffect-1
useEffect-2
useEffect-3

However, further calls will depend on which variable gets updated

0

useEffect are called in the order in which they are written in the code and depending on which useEffect's dependency leads to its execution

Also state updates are async and and any use of setX or other state updaters will only be updated once all executions of useEffects are completed which is why console.log(x) shows 2 instead of 1

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400