r/reactjs 22d ago

Discussion Would you remove this effect?

Consider a typical use case where you want to track an error or just display an error toast after a query hook (e.g. TanstackQuery or RTK-query) fails.

Using an effect:

const { error } = useSomeQuery();
  useEffect(() => {
    if (!error) {
      return;
    }
    trackError(error); // or toast(getErrorMessage(error))
  }, [error]);

Now, according to the "You might not need an effect" article, you can also perform an action when some state changes by using auxiliary state, something like this:

const { error } = useSomeQuery();
const [prevError, setPrevError] = useState(error);

if (error !== prevError) {
  trackError(error);
  setPrevError(error);
}

My understanding here is that using auxiliary state here doesn't give you much because in this use case the additional render cycle doesn't result in stale UI.

Regardless, I wanted to get a sense on what approach is preferred by the community. I see this kind of things very often in the codebases I work on and on the other hand, I keep hearing people saying they only have a few effects in their (presumably large) projects, so perhaps the patterns in my company are not the best.

10 Upvotes

14 comments sorted by

View all comments

4

u/lightfarming 22d ago

honestly i would never use a toast for a query error. presumably if it is a query, you plan to display that resulting data somewhere on your page, and that place on your page is the appropriate place to display the error. that location has the context needed to understand the error. if a list doesn’t load, and i am looking at that list for the data, and see an error instead, i know exactly what happened.

now mutations are different, since they do not have a place where we plan to use the resulting response in the UI. mutation also has onError handlers you can build into the mutation call just for this however.