React Query Tutorial #2 - The useQuery Hook
Key Takeaways
Uses the useQuery hook from React Query to manage async data in React components, fetching data from the Star Wars API
Full Transcript
okay then gang so now we've got the bare bones of this website sorted we can switch between these two different components now we want to start using asynchronous data so start making requests to this api right here the star wars api to add some data to our different components now we're going to use the react query library to manage our asynchronous data in particular in this lesson we're going to use a hook from that library called use query so the first thing we need to do is import that hook in one of our components i'm starting with the planets component and remember we already installed the react query library in the first tutorial of this series so let us now import something from that library use query from react query so this is a hook that we're going to use to manage our asynchronous data so let's set this up down here first of all i'm going to say const and we're going to destructure a couple of different properties from this later on for now i'll leave that blank but we'll set it equal to use query and inside this hook we need to pass in two arguments the first argument is gonna be a key for this query so a descriptive name and it's gonna be a string for now so i'm going to call that planet you can call it what you will i'm calling it planets because we're going to go fetch some planet data the second argument is going to be a function an asynchronous function to go and grab that data so i'm going to call this fetch planet but again call it what you will so now we need to make this function to go out and grab the data so i'm going to say const fetch planets is equal to an asynchronous function and we're going to use the await keyword inside here first of all i'll say const response is equal to fetch we'll use the fetch api to grab the data and we need to pass in an endpoint right here to get that data so i'm going to grab that from swappy right here and we want this end point which is for the planets we don't include that one because that would get us one planet we want a list of planets so i'm going to paste that in here as a string and just add in the colon and double forward slash okay so this right here is going to go out and grab the data but it's asynchronous it returns a promise and i want to wait until that promise is resolved before i assign the result to this variable so i'm going to use the awake keyword to do that so that's how async and await works because we've marked this as an asynchronous function we can use the awake keyword to wait until this is complete before we assign the result right here so now we have that we can do something with it so when we use the fetch api right here to grab data we need to use the json method on the response to access the data from that response and i'm going to return that so i'm going to say return the response dot json and that gets us the data okay now this is also asynchronous in nature it returns a promise so right here we're specifying that this is the function that's going to go out and get that data now use query is going to manage all of this fetching under the hood it's going to call this for us initially to grab the data but then later on it's also going to cache the data and refresh the data in the background when it needs to do so so it's going to manage that for us we don't need to manually call this later so from this we can extract two different things here we can get the data which is the result of this thing right here and also a status and that's the status of the query is it loading is there an error is it a success that kind of thing so first of all let's log this to the console and see what it looks like console.log data and save that and then over here in the browser let's open up the console and if i refresh we can see this data logged out to the console several times and that's because of the component reloading but it's only actually ever fetched once we're not fetching it four times so if i go to the network tab and limit this to just fetch requests i'm going to refresh and we can see just one fetch request to this endpoint it only ever does that once even though in the console we log it out four times okay so now we have this data right here and we can use that to map through the different results that we get now if we take a look at one of these things you can see right here we have the results and there's ten of them now the count property on this says the 60 but it only sends us 10 at a time and it says right here to get the next lot we use this endpoint we specify a page right here as a query parameter so we'll do that later on for now let's just stick with the first 10 that we get now i said also that we have this status thing right here so let's output this in the dom let's just say we want a p tag right here and then we're going to output the status right here as well so remember the status is the status of the query if i save this and return over here you see straight away initially it was loading while it fetched the data but then its success once we have the data if i refresh you'll see that again quickly it's very quick so you're only going to see it for a split second but you did see loading initially now if there's an error so for example if i add something else to this like a d at the end that's not a valid endpoint so it can't fetch the data using that endpoint it should error and the status should show an error as well but it will try to fetch this three times before it shows an error over here but once it fails after those three times eventually we will see the error status and there it is so we have this error right here so at that point we could display an error message to the user so what we really want to do is check the status inside our template and output maybe a different thing depending on the status if it's loading we could show a loader or say something like data loading if there's an error we could show an error message and if we have the data then we want to output the data that makes sense right so let me first of all comment out the status right here and instead let's do a few different checks so the way we're going to do this is by using the logical and operator for each one of these so let me just write this out then i'm going to explain it so we're going to evaluate the status first of all and we're going to see if that is equal to the error so this is the error case right and then we're going to use logical and right here and then do a bit of template inside parentheses so this template is just going to be a div right here that says error fetching data okay so now how does this work well this right here is going to evaluate to either true or false and this template on the other side of the logical and is only ever going to be output if this is true so if this on the left is true then we see this now it's only going to therefore output if we have an error right does that make sense so we can do the same thing for loading and success so let me copy this and above that i'm going to do the loading one so is status equal to loading if it is then we'll just output loading data so loading data dot dot and below that we want another one as well and this is going to be the actual data so once we have the data and the status is success ta-da then we want to actually use that data and output it to the dom now remember if we take a look at this data over here then oops we need to update this endpoint again so it is valid save it and if we take a look at this data remember the actual data is in this results property and this is an array of data so we want to cycle through this results property and output the data for each one of these so let's use a map method to do this and again if any of this is over your head maybe check out my earlier react tutorials the playlist to those are down below just to brush up your knowledge and react first of all because i am moving quite quickly over this assuming you already understand the basics of react and outputting data so anyway now we'll have a div and oops not a sieve we want a div and inside that div we want to map through the data and output a bit of template for each one of those different planets that we get back so we want to take the data first of all then we want the results property on that and then we want to map through those so this fires a function for each one of these and then we can return a bit of template for each item as well so in that function we take the planet that we're currently iterating so that's going to be the first then the second and the third etc and we could just if we wanted to return a div for each one and inside this div we could just output the planet name for example so planet dot name like so now if we check this out in the browser then we can see all of the names of those planets now it's telling us to add a key prop and that's when we cycle through data and output a bit of template for each item of data we need to assign a key prop to each one of these different elements so that react can keep track of them now we're not going to apply it to this because instead we're going to create a custom component instead of outputting the template right here so for each planet we'll have a planet component so new file and planet.js over here and inside this i'm just going to paste this in because i don't want to bore you in creating a react component from scratch but all we're doing is importing react then we have the planet component we're grabbing this planet property from the props which we're going to pass through to that and that is going to be this thing right here the individual planet we're iterating and then inside we have a bit of template we have a div with a class of card which we're going to style up later then we have an h3 for the planet name and then we have the population of the planet and the terrain of the planet and these are all properties on the data that we can use if we take a look inside here each planet has a name it also has a terrain which we use and also a population right here okay so now we have this component and we're exporting it now we can import it into planets up here let me do that import planet from dot forward slash the same directory and we want the planet component and so down here now for each item we can use the planet component so planets like so now remember we need to pass through as a prop the individual planet so we'll do that planet is equal to planets and also each one of these remember needs a key so react doesn't complain so the key is also going to be the planet.name because that is unique for each planet okay so now let's see if this works so let me zoom over here and now we can see all of the planets right here output to the dom right looks good we have the name the population and the terrain over here as well so first of all let's just style this thing up a little bit remember we added a class of card to this so i'm just gonna style up that card so to do that let me go to index.css and come to the bottom and paste in three different rules we have the card itself some padding a background margin and border radius the paragraph tag inside that and also the h3 which is going to be yellow so if i save that and come back over here that looks a little bit better so that's nice now react query is doing all of this for us under the hood we're using it to first of all fetch the planets using this function then once it has those it gives us the data but in the meantime it also gives us the status so that we only output once we have the data and we can output something else dependent on that status so once we have that data we're then cycling through it and outputting each planet in the dom so now we just need to quickly do the same kind of thing but this time for the people instead now instead of writing all of this out from scratch i'm going to copy this dude and paste it over here like so and now i just need to replace a few things so first of all anywhere where we have planets i need to replace that with people so this and this i think that's it and also this right here we'll call people and we want to fetch people not planets this time and the same goes for this people now the end point for this is just people like so and i think if we go down do we have any more okay let's change the title back to people and down here we also want to map through the data but this time we're taking each person and also we need to create a person component so let's do that new file and person.js and again i'm going to copy and paste this from my github repo so right here we import react we have the person component we're going to take in the individual person we have a class of card on this div i'll put the name the gender and the birth year of that person so this is all data we get back from that endpoint so now instead of importing the planet right here we want to import the person instead and we want to output that person component down here and this right here needs to be the person name and this and this needs to be person instead so we're passing through the person prop and that is the value we get right here so now fingers crossed this should all work i've probably made a mistake somewhere along the line but what on planets originally if i go to people we see loading very quickly then we get the people planets people now notice this the second time that we go to these and the subsequent times that we go to these we're not seeing the loading message and that's because we're using cached data but in the background react query and the use query hook is refetching the data just to see if there's any update and if there is an update we would show the updated data instead so it's always going to stay in sync but we're using this cached data so we have a better user experience until we perform that check now when it performs that check there's no need to update the data because it's always the same but if there was a change it would update it for us so that's a really nice user experience if we refresh the app though and then try to fetch these again we will see the loading message very quickly so it has to fetch it the first time because we don't have it initially so that's the basics of the use query hook right there to manage our asynchronous data but react query can do a lot more than just this and we're going to see some of the things later on but first of all in the next video we're going to look at something called the query dev tools and also a bit of config that we can pass through to this hook
Original Description
In this React Query tutorial we'll go over how to use the useQuery hook in order to get & manage async data in our React components.
SWAPI - https://swapi.dev/
🐱👤🐱👤 JOIN THE GANG -
https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join
----------------------------------------
🐱💻 🐱💻 My Udemy Courses:
+ Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript
+ Vue JS & Firebase - http://www.thenetninja.co.uk/udemy/vue-and-firebase
+ D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase
🐱💻 🐱💻 Course Files:
+ https://github.com/iamshaunjp/react-query-tutorial
🐱💻 🐱💻 Other Related Free Courses:
+ React Tutorial - https://www.youtube.com/playlist?list=PL4cUxeGkcC9ij8CfkAY2RAGb-tmkNwQHG
+ React Hooks (& Context) Tutorial - https://www.youtube.com/playlist?list=PL4cUxeGkcC9hNokByJilPg5g9m2APUePI
Download node.js - https://nodejs.org/en/
Get VS Code - https://code.visualstudio.com/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: AI Pair Programming
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
Dev.to AI
🎓
Tutor Explanation
DeepCamp AI