-1

I am new to react hooks and as i read in docs useEffect runs on every update of component and on first render also (so it is componentDidMount and componentDidUpdate combined) but when i am fetching data inside useEffect it will re-do it when state updates and so if I set state value after fetching data from server it will create infinite loop. and i want to prevent it and only fetch it for first render like in componentDidMount, how can i implement this?

iLiA
  • 3,053
  • 4
  • 23
  • 45

1 Answers1

2

useEffect() takes a dependencies as an array parameter. This dependency(ies) acts as a decider such that, if one of the dependencies' value change, useEffect is invoked.

It's effectively equivalent to saying:

shouldComponentUpdate(nextProps, nextState) {
 // If props or state changes, update the component
 if(this.props.someProp != nextProps.someProp  || this.state.someState != nextState.someState){
   return true;
 }
 return false;
}

With useEffect() :

useEffect(() => {
  //Do stuff here
}, [somePropValue, someStateValue]);

But to say that only do once, specify an empty dependency array(ideal for API calls that happens once on load):

useEffect(() => {
      //Do stuff here
    }, []);
Karthik R
  • 5,523
  • 2
  • 18
  • 30