Elwin's Blog

an activist who likes to think

front cover

Avoid triggering multiple times on a useEffect when changing multiple state

Posted on

Image in the following scenario:

You have a useEffect that watches the event_id and the date_range, they are separate states from useState.

when one of them changes, it will re-query a list of events. The user can change the event_id from a list of events, the user can also change the date_range by using the date picker.

Somehow, you got a new request that when an active event_id is changed, the date will reset to the default date instead of stay as it is.

How would you change your code, so when a user selects a new event, it will only trigger the API call once?

I got this question from a junior college last week, it's not the first I have been asked about this question, nor will it be the last time, I believe, it's not uncommon to meet such a scenario when coding a reactive web app.

For me, there are two options I can choose, each has its's trade-off:

  1. Group the action to set both states in a function, this is easier to do, but if they are called multiple times on different places, it will look ugly, this is when I will choose option 2 (beware(until we reach React 18, don't put an async action between setting the state, otherwise it will cause an extra render.)

  2. Group the event_id and date_range together into a useReducer, this makes sense since they are closely related to each other, and you can easy to update both state at a single event, it will look cleaner when reading, but it does require extra effort and space to transfer them to a useReducer,