Error Handling with React Query
Today, I'm going to talk about error handling with React Query.
It is sometimes difficult to handle errors from asynchronous tasks in React apps. React Query is an excellent library for managing asynchronous states, and it is essential to know how to do it with this library. In this way, we will have controlled not only the happy path in our app but also all kinds of errors.
Some developers focus on happy paths and leave error handling to the last minute or barely even address it. That's not good because, as you already know, errors in all types of apps eventually occur at some point.
Handling errors with React Query like a senior front-end developer
There are 3 ways to handle errors:
The standard way
Using Error Boundaries
Using onError callbacks
Let's dive into each one.
The standard way
You can handle errors from the isError flag:
If you have to do this in every component that wants to use a query, it can end up in a boilerplate code.
Using Error Boundaries
You can add it (useErrorBoundary: true)
to each useQuery:
Or add it globally to the React Query config. It applies to all queries of the app:
React Query throws an error when an error happens, and React will catch it with the closer Error Boundary.
Using onError callbacks
You can add it to each useQuery:
Or add it globally to the React Query config:
The onError callback will apply once for each query. Otherwise, it will apply whenever you use the useQuery. If you use the same useQuery in 2 different components, the onError Callback will apply 2 times if you use the first option.
Conclusion
Always keep in mind that it is essential to handle errors in your apps. If you are using React Query, these 3 ways will help you to do it. I mainly use the last two as they allow me to make less boilerplate code and more maintainable.
Here, I share a helpful resource that also talks about this topic. I strongly recommend it:
https://tkdodo.eu/blog/react-query-error-handling
It’s a blog by Dominik, one of the co-maintainers of the React Query library, where he shares amazing articles about the library.
I hope you enjoyed the article.
Join my weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!