nico
Published in : 2022-02-18

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 Date : 2022-02-18

Best answers

51

Best answers

51

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 Date : 2022-02-18

Best answers

4

Best answers

4

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 Date : 2022-02-18

Best answers

4

Best answers

4

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 Date : 2022-02-18

Best answers

4

Best answers

4

It seems to work like expected.

I also found but didn't try:

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

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Reload browser window using Reactjs?
Publish date: 2022-02-08 | Comments: 4

Tag: React js

React Component displaying a list of lines
Publish date: 2022-03-19 | Comments: 3

Tag: React js

React Redux : Connect is not called
Publish date: 2022-03-02 | Comments: 1

Tag: React js

Unexpected mix of '&&' and '||' Reactjs
Publish date: 2021-10-30 | Comments: 0

Tag: React js

Export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'
Publish date: 2022-04-02 | Comments: 2

Tag: React js