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

Module not found: Can't resolve 'swiper' in Reactjs [Solved]
Publish date: 2021-10-03 | Comments: 1

Tag: React js

How to use Datepick of Mui with Formik
Publish date: 2022-02-14 | Comments: 7

Tag: React js

React.Fragment. React.Fragment can only have key props and children
Publish date: 2022-08-06 | Comments: 2

Tag: React js

React usestate array map() is not working
Publish date: 2022-04-22 | Comments: 3

Tag: React js

[solved] Render/Show a custom option in Autocomplete Material UI?
Publish date: 2021-12-22 | Comments: 2

Tag: React js

npm install @mui/material returns error
Publish date: 2022-04-02 | Comments: 1

Tag: React js