Home > Software design >  How to execute useEffect in order?
How to execute useEffect in order?

Time:10-16

I want to execute useEffect in order synchronously.

const [first, setFirst] = useState([]);
const [second, setSecond] = useState([]);
const [third, setThird] = useState([]);

function firstFunc(array) {
  for (let i = 0; i < array.length;   i) {
    array[i]   1;
  }
}

function secondFunc(array) {
  for (let i = 0; i < array.length;   i) {
    array[i]   2;
  }
}

function thirdFunc(array) {
  for (let i = 0; i < array.length;   i) {
    array[i]   3;
  }
}

// 1. first useEffect
useEffect(() => {
  setFirst(firstFunc([1, 2, 3]));
}, []);

// 2. second useEffect
useEffect(() => {
  setSecond(secondFunc(first));
}, [first]);

// 3. third useEffect
useEffect(() => {
  setThird(thirdFunc(second));
}, [second]);

As this code, with useEffect I execute the first useEffect to update first state.

and once first state changes, after that, I want to update the second state.

after that, I want to update the third state.

In order to do this, I code like above with dependency.

But sometimes in practice it doesn't work as I expected, not in order.

Please help me what is the problem and how to achieve my goal.

CodePudding user response:

in your second and third useEffect check if your dependencies are empty or not. if not empty then execute the functions. i write the second useEffect code for you so you can figure out how it works.

useEffect(() => {
  if(first.length>0){
     setSecond(secondFunc(first));
  }
  
}, [first]);

CodePudding user response:

The state update using the updater provided by useState hook is asynchronous, and changes will not be reflected immediately. Consider using useRef or a dependency like react-useStateRef instead.

useRef example:

const first = useRef([])

useEffect(() => {
  first.current = ['Hello', 'World']
})

useEffect(() => {
  console.log(first.current) // Will print ['Hello', 'World']
})

react-useStateRef example:

import { useState } from 'react-usestateref'

const [first, setFirst] = useState([])

useEffect(() => {
  setFirst(['Hello', 'World'])
})

useEffect(() => {
  console.log(first) // Will print ['Hello', 'World']
})
  • Related