Back to posts

Simple ways to manage state in React - Server state

July 30th, 2022 - 4 minute read

Winter Wonderland in Sweden, by Fanny Gustafsson

In the first part of this series, I talk about managing the UI/Client state. You may wanna check that out before reading this post.

Server state is state that is on the server and is served/used on the user’s end, e.g, a list of posts, user’s records. It is different from client state and should be handled differently.

Many React devs put all things state inside a library like Redux. The idea is a single source of truth. This is not very ideal in a few ways. One of the primary sources of a slow React application is global state. Not a lot of states need to be global. And the truth is, you don’t need Redux.

Server state has a few challenges including caching, deduping requests, background updates, mutations, paginations, etc. Personally, I think caching is one of the hardest concepts in computer science.

How then can we approach these problems? React Query. Yup, that’s it! According to their docs, React query (now, Tanstack Query) is a Powerful asynchronous state management for React.

Right away, let's look at an example. Feel free to play around with this app.

Posts

Loading...

Create Post

Notice that the first time you visited the posts, you saw a `loading state/spinner` which is the case with SPAs. However, after you returned to the post list and clicked on any posts you had already visited, you'll see them load instantly and background refresh right before your eyes! (You may need to throttle your network speed to simulate longer loading sequences.)

React query is awesome!

Here's what the code looks like.

ts

Just like that, React query eliminated most of the loading spinners in our SPA (Spinner Page Application 😅). Our app is awesome, it feels great, is very fast, and is maintainable too.

Conclusion

I believe a tool like react query is the future for handling our asynchronous data.

Not only does it solve the challenges with server state, but it also helps us model our global state and think about our global state with a new perspective, and in most cases, it even removes all of it or most of it from our application.

Here's what Kent C Dodds has to say about react query:

"React Query is the missing piece to React application development that I've been looking for after years of building React apps. Finally, I have a tool that gives me exactly what I need to solve my application state management problems without giving me more problems. It's fantastic."

That's it for this post. Use react query to manage your server cache. Thank me later.