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?
Asked
Active
Viewed 256 times
-1

iLiA
- 3,053
- 4
- 23
- 45
-
2Can you share your code? normally you pass an array to `useEffect` in a way that prevents infinite loops. – Hamza El Aoutar Oct 31 '19 at 09:46
-
yeah thanks, passing array worked – iLiA Oct 31 '19 at 09:50
1 Answers
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