Home > Mobile >  ReactJS hooks: update state inside condition
ReactJS hooks: update state inside condition

Time:06-22

everyone!

Can some one tell me if updating state inside if / else statement is acceptable by React rules. In particular updating state based on the result of a promise inside of the condition.

For example:

import {useState} from "react";
import {somePromiseOne, somePromiseTwo} from "./example";

function example(){

  const [state, setState] = useState();

  if(true){
    somePromiseTwo().then((result) => setState(result));
  }else{
    somePromiseOne().then((result) => setState(result));
  }

}

CodePudding user response:

It is acceptable to use state inside condition. If you want to know what are rules of React hooks you can read about it here: https://reactjs.org/docs/hooks-rules.html

CodePudding user response:

Yes why not :

const promiseFunc = isCondidtionValid ? somePromiseTwo : somePromiseOne;
promiseFunc().then(result => setState(result));

CodePudding user response:

The Rules of hooks states that you must only call a hook at the top level, meaning you can’t call it inside a conditional branch. However, it is perfectly fine to call the setState function it inside a branch because it is not a hook itself, just a function to trigger a state update.

So it is fine to do A but not B

// A: Valid
function example(){
  const [state, setState] = useState();
  useEffect(() => {
    if(true){
      somePromiseTwo().then((result) => setState(result));
    }else{
      somePromiseOne().then((result) => setState(result));
    }
  }, […]);
}

// B: not valid

function example(){
  if(true){
    const [state, setState] = useState();
  }else{
   // …
  }
}

However, note that I put your async logic inside a useEffect hook. Why? Because your function can be called an arbitrary number of times by React, and you don’t want the async logic to trigger every time it is called. The idiomatic way to control when and how often it is called in a custom hook/component in React is by using useEffect. You can read more about it here

CodePudding user response:

Yes, it is acceptable. For example:

Promise.resolve().then(() => {
  setState("newState");
});

would work just fine.

  • Related