React: is useEffect always the correct way to go?

Viewed 64

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 query which is just a query for backend. A query also knows a sorting. This will be filled by a loadQuery method, which gets a configured query from backend. But the initial state is a empty query and NOT undefined.

  • a method loadData which loads data from backend of type Entity[]. This method consumes the state query. This can directly be triggered, because of the empty query which is a valid query.

  • a method loadView which loads views from backend of type View. A view is just a JSON, which describes the cells of a table and has a sorting property.

  • a useEffect, which calls loadData and loadView. As dependency, we have the query.

  • a useEffect function which listen on the loaded view. If the loaded view has a sorting property, then it will manipulate the query state. This will lead to trigger the useEffect again from one point above.

This is the current scenario (shortened of course). We also have

  • view switch button, which changes to query again. This will lead that the useEffect for loading data will be triggered.
  • a infinity loading in the table (which will also call loadData with an offset),
  • The query can change, if the user changes the query in a FilterDialog

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 :)

0 Answers
Related