I am currently asking myself, if useEffect is always the right way to go. I am thinking about that, because of my current project.
Imagine you have to following:
a state
querywhich is just a query for backend. A query also knows asorting. This will be filled by aloadQuerymethod, which gets a configuredqueryfrom backend. But the initial state is a emptyqueryand NOT undefined.a method
loadDatawhich loads data from backend of typeEntity[]. This method consumes the statequery. This can directly be triggered, because of the emptyquerywhich is a valid query.a method
loadViewwhich loads views from backend of typeView. Aviewis just a JSON, which describes the cells of a table and has asortingproperty.a useEffect, which calls
loadDataandloadView. As dependency, we have thequery.a useEffect function which listen on the loaded
view. If the loaded view has asortingproperty, then it will manipulate thequerystate. This will lead to trigger the useEffect again from one point above.
This is the current scenario (shortened of course). We also have
viewswitch button, which changes toqueryagain. This will lead that the useEffect for loading data will be triggered.- a infinity loading in the table (which will also call
loadDatawith an offset), - The
querycan change, if the user changes the query in aFilterDialog
Sometimes the useEffect for loading data, will be triggered 3 times in a row.
Sure, a solution will be to remember a boolean if some data got already loaded or not... But since we have more then one useEffect, it is hard to do this. It is also hard to remember a boolean for this, because if a componentDidUpdate cycle occurr, then you have to reset these booleans, because everything should be executed as before. But this can lead to problems, because everything is async.
Maybe some one else had the same problem, to have too much useEffects and this leads to unnecessary things and can share his experience with me :)