Modern State Management with Tanstack Query


Frontend state management has a nearly endless amount of overcomplicated solutions to what, to begin with, is a complex problem. Traditional solutions like the well-established Redux State Management library are being pushed out by newer and more user-friendly solutions that integrate better with the always-ready state of many web-based applications.

Though Redux doesn't natively support data fetching from an API in a user-friendly way, once the Redux toolkit is added it brings it almost to par with more modern solutions.

I wouldn't consider using Redux Toolkit's Query package is that it's grafted onto an existing library and trying to get it to behave predictably and store the data in a normalised store or having a cache key is difficult.

On the other hand, Tanstack Query, fully typed and with many features that RTK is missing, is designed from the ground up to retrieve data from an API and, if needed, update that data using a WebSocket connection.

Another reason to use Tanstack over Redux Toolkit is the sheer wealth of examples that the Tanstack Query docs exhibit. It allows the developer to exactly see how the code behaves in an isolated environment. This is a pattern that many Tanstack packages follow and that I hope many more will adopt in the future, making the lives of developers immeasurably easier.

Caching, the hidden obstacle to any application is handled differently in both libraries. RTK Queries don't have an expiry time, so once data is fetched, it remains the same unless it's explicitly updated. On the other hand with Tanstack Query, every query has a stale time. Basically, a set time period before the data becomes stale and needs to be refreshed.

In Tanstack this behavior is nearly infinitely customisable per-query or globally if you really want to.