Lesson Description

The "TanStack Query Exercise" Lesson is part of the full, State Management at Scale in React & Next.js course featured in this preview video. Here's what you'd learn in this lesson:

David instructs students to refactor a component by replacing multiple useEffect and useState calls with TanStack Query. He demonstrates setting up a query client, using useQuery for fetching, and explains how it simplifies code and handles caching.

Preview
Close

Transcript from the "TanStack Query Exercise" Lesson

[00:00:00]
>> David Khourshid: In this exercise we're going to actually be using Usequery and replacing a bunch of useEffects and use date to fetch data with Tanstack Query. If you need a reference to where or like how to do it, then I would really recommend you go to tanstack.com query I believe.

[00:00:24]
And there are some starter guides over here. It gives you an overview of how to fetch data using Tanstack Query. So we'll take a couple minutes and we will refactor this component. So if we go to Fetch page, there's a couple of places where we're fetching data. You could see it over here, we're fetching flights, and over here we're fetching hotels.

[00:00:51]
So what I want you to do is convert this to using Tanstack query just to get a feel for using third party libraries for fetching data and how much boilerplate code it actually removes. All right, so here's how we could get rid of all of those useEffects and use dates and just make our code a lot simpler.

[00:01:16]
The first thing that we need to do is, and this is honestly the tiniest bit of boilerplate for React's query, but it's required by it, otherwise it will yell at you. You want to first create a query client. And this comes from Tanstack React Query. And this query client is the central place where it's basically going to hold that cache.

[00:01:42]
So you might think of Tanstack, like React Query as, as a data fetching library. It's actually not. It's more of a local cache library that just works really well with Async data, and that's sort of its primary use case. The other thing that you're going to want is a query client's provider.

[00:02:06]
And so this also comes from Tanstack Query, you pass the clients into it. And so what this is going to do is anything that uses Usequery, use mutation inside of your components, it's going to be able to read that query client and use it. So now let's get rid of these useEffects.

[00:02:26]
So let's look for this one. We're loading flights over here. It's time to make some code disappear. So we're going to get some stuff. We don't know exactly what this is yet, but we're going to use Query and the first thing that we're going to do is we're going to pass in the query key and this is just going to be our flights and we are going to put in our flight search.

[00:02:57]
So flightsearch and then we actually have to fetch the data. So that is our query function and we're going to pass in the flight search to it. And also I need to import this. And so this is going to give us a few very useful things. It's going to give us data, it's going to give us an error if there is an error.

[00:03:22]
And it's also going to give us some very handy booleans. So it has is loading. And if you really want to, instead of using the Booleans, you could use status, and that way is loading equals, status equals, and then you have error pending or success. So internally, Tan Stack Query maintains its own state machine for dealing with these requests, but for now we're just going to use is loading.

[00:03:54]
And so now we could get rid of this state. And, and we don't need this anymore or this or actually we don't need any of this because if we just rename this to flights, we no longer need this or this. And now we're just using Tanstack query for it.

[00:04:18]
Now, before I save this, I want to show you the difference between, you know, using Tanstack query and not using it. So if I go to fetch. Error has already been, all right, actually I'll just do this. I'll save it. Anyway, so we have error over here. It's gonna be error message, I think that that's good.

[00:04:46]
Okay, so now let's search for a flight to Tokyo departing soon. So we are going to get our flights. Now, if we go back to search and we don't change anything and we search, we instantly get the results again. And the reason is because it's cached. So this is one of those things where this would require even more code to implement.

[00:05:12]
And it is a very useful feature to have so that you don't make unnecessary API requests and you don't keep your users waiting for too long. So now when you select a flight and you change the hotel, if I go back to search and I search for hotels again, it's going to keep on searching.

[00:05:33]
And that's because we didn't implement a caching layer. And so it's not using react query, it's just going to keep fetching over and over again. But hopefully you could see that we removed a lot of useStates. We removed a big useEffect and we're just replacing that with a single usequery call.

[00:05:55]
It's like one of those things that people wish were just built into React because it's such a useful library.
>> Speaker 2: One. Major difference between the older versions of React Query and the newer one is the is pending versus is loading. Because used to be is loading was just like anytime it was fetching data, but then they changed it to be pending.

[00:06:23]
Because there are times when you wanted to show a loader if it's like refetching versus when it's just initializing the first fetch and then just showing whatever's cached and then updating with whatever is cached. And so I had to make sure that when I was upgrading in that process that I used the proper key.

[00:06:47]
>> David Khourshid: Yeah, that's a very good thing to point out, there is a subtle difference. Thankfully, if you do hover over, it does tell you when each one will be active, and I think this one is different. Is true whenever the first fetch for a query is in flight, right?

[00:07:02]
>> Speaker 2: Yep, so it's a combination of both isFetching and isPending.
>> David Khourshid: Yeah. Awesome.
>> Speaker 3: As someone new to React Server components and Next js, it sounds like I'd reach for Tanstack query for any use client component, or does this also play well with server components?
>> David Khourshid: I would say it's either or.

[00:07:25]
So with server components, the idea is that you're awaiting your data like in the component itself, and actually let me search for. Let me search for one of these. So something that I forgot to mention is that this entire app, besides just the exercises, is a flight itinerary booking app that I have started to build.

[00:07:53]
So it is messy, but it is also a good way of just putting you into a real world app that is in progress. So I do invite you to like, if you want to finish the app, play around with it. It's something that I did start, but this would be an example of using a server component.

[00:08:11]
So notice that there's no use clients, we have an itinerary page. I'm using a database to just get my itineraries and I'm actually awaiting this directly inside the component. So yeah, you could also use Suspense. I believe I have. Yep. I have one page where I am using Suspense and this is for like showing the flight results and actually let me just demonstrate that to you real quick.

[00:08:40]
Again, this is extremely half built, but let's say that we have a trip to Minneapolis and we're just doing stuff. We create the itinerary, and then we want to add a destination. So this is just like a fully featured or a fully featured app in progress. And then like if you're booking flights, you're going to see suspense in action because we have this, we have our flights, and this all happened within the same page.

[00:09:17]
So. Yep, there's suspense in action as well. Then we have some hotels for us to choose from. Yeah. So I would really recommend reading the react docs on using server components and suspense. And there's also a few front end master's courses on that too that go much more in depth than I will in this course.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now