handling loading for multiple useEffect that run different things

Viewed 656

I'm starting to use Hook and I have a problem to handling multiple useEffect

current Hooks code:

//1st useEffect should run only on DidMount
React.useEffect(()=>{
  //Calling API only on didMount
},[])

//2st useEffect should run on Context value Changes
React.useEffect(()=>{
  //Processing Context Foo and Context Bar on didMount and didUpdate
},[foo, bar])

My Expected Result is to add a loading while 2 useEffect is run on didMount

I can achieve it by using class Component like this

  componentDidMount(){
    this.setState({isLoading:true},()=>{
      //Call API
      
      //Processing Context Foo and Context Bar

      //on CallAPI and Processing Context is done
      this.setState({isLoading:false})

    })
  }

how can i achieve it using Hooks?

2 Answers

This can be simply done by defining multiple is-loading states with the useState hook. We can have either

const [isLoading, setIsLoading] = useState({ first: true, second: false });

or

const [isLoadingFirst, setIsLoadingFirst] = useState(true);
const [isLoadingSecond, setIsLoadingSecond] = useState(true);

After this, you can update the is-loading state which is related to the useEffect

More details on useEffect and useState can be found React Hooks cheat sheet: Best practices with examples

  const [isLoading, setIsLoading] = useState(true);

  React.useEffect(() => {
   setIsLoading(true);
    //Call API

    //on CallAPI and Processing Context is done
   setIsLoading(false);
  }, []);

you can do same thing using hooks.

Related