user2443507
user2443507

Reputation: 393

Multiple useState in useEffect, order of execution

What happens after the render due to the first useState? Does execution begin immediately at the second useState?

   import React, { useState, useEffect } from 'react';
    const [var1, setVar1] = useState();
    const [var2, setVar2] = useState();
    ...
    useEffect(() => {
        if (var1) {
          setVar2('abc')
          setVar1('zyx')
        }
    }, [var1]);

Upvotes: 6

Views: 8551

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14385

If I'm understanding your question correctly:

useEffect's runs after the render. So the execution would be:

  • useState 1
  • useState 2
  • return
  • useEffect (only run if your dependencies change)
  • re-render

Inside your useEffect, the setVar2 setter will be called before the first. But remember that setting state is async, so the first executed does not mean the first to finish.

To answer the more specific question about the order of execution inside an effect consider the console logs in your example:

const TestEffect= (props) => {
  const [test, setTest] = React.useState();
  const [test2, setTest2] = React.useState();

  React.useEffect(() => {
    console.log('effect was called')

    setTest2('test2');
    console.log('set test 2 called')

    setTest('test');
    console.log('set test 1 called')
  }, [test])

  console.log('render')
  return <div>Test</div>;
}

// Output:

// render
// effect was called
// set test 2 called
// set test 1 called
// render
// effect was called
// set test 2 called
// set test 1 called
// render

Upvotes: 7

Related Questions