nico

18 Feb 2022

Why is UseEffect called all the time when the dependency is an array of one object ?

React js

I have one app which add data with a POST http request.

I want to useEffect to reload the data which dispatch a GET http request with onGetData. the problem is it is called all the time.

It seems to be because the dependencies of useEffect is one array of one object reference
And this object reference is changed each time we map from the redux state to the component props (in mapStateToProps).

What can I do to either avoid useEffect called all the time? or Can I add another check instruction before calling onGetData.

Thanks for your help :)

 useEffect(() =>

 OnGetData('/MyData/Load')), 
 [myData]);
 
 function mapStateToProps(state) {
 
 return {
 myData: state.myData
 };
}

Comments

Mohamed Atef

18 Feb 2022

githubgithubgithub

From what I see that you want to call it one time only? 
It's already being called one time when the component finishes loading, If it is repeated we can use a condition like If the data exists don't update it

nico

18 Feb 2022

Best Answer

best answer

I found a react hook called use-deep-compare-effect on npm which tackles with this very same problem I raised !

//github.com/kentcdodds/use-deep-compare-effect

I will try it and paste the code when I'm done.

Cheers

nico

18 Feb 2022

Dear Mohamed, 

I just needed useEffect to be called when myData object is updated (for example when I add or update data on the myData object).

So useEffect should be called only when we called the http post to add/update and got the new data.

I found a hook which looks promising : //github.com/kentcdodds/use-deep-compare-effect
 

It's React's useEffect hook, except using deep comparison on the inputs, not reference equality

nico

18 Feb 2022

It seems to work like expected.

I also found but didn't try:

//github.com/sanjagh/use-custom-compare-effect

© 2024 Copyrights reserved for web-brackets.com