React Query Makes Writing React Code 200% Better

Web Dev Simplified · Beginner ·🛡️ AI Safety & Ethics ·3y ago

Key Takeaways

The video showcases React Query, also known as TanStack Query, a library that simplifies writing React code by handling caching, cache validation, and refetching, and demonstrates its features and usage in various examples.

Full Transcript

if you've ever used Fetch and use effect to manage API calls you know how much of a pain and a headache it can become on even small scale applications this is why I love tan stack query also known as react query because it handles all of that nonsense like caching cache and validation and refetching behind the scenes for you 10 set query is amazing and in this video I want to give you an overview of what tan stack query is how you can use it and give you some examples of it in real world projects [Music] um welcome back to web dev simplified my name is Kyle and my job is to simplify the web for you so you can start building your dream project sooner in this video we're going to be talking about tan stack query now most of you probably notice as react query because it was originally react query but tan stack has made queries so you can use it inside of a bunch of different Frameworks Beyond just react that's why the name is changed to tan stack query but most people know this as react query and the thing that's so great about this is the fact that it handles pretty much everything you could ever want with accessing a server all for you behind the scenes and this really means that you can spend your time working on writing your actual code for your project which is the fun stuff instead of worrying about handling things like caching and cash and validation because everybody knows caching is an absolute pain and this just takes care of it for you so for pretty much the rest of this entire video I want to go through a simple example project of how I use react query inside of this and all the different features that it has now this isn't going to be a full blowing tutorial covering everything there is to know about react query I'm going to have a video on that coming out later I'll link in the cards and at the end of this video for you but essentially I just want to give you an overview of what this is so you get an idea if this is something that you want to use in your project or if it's something you're going to pass on so for this very simple project all we have is we have essentially a list of posts and you can see if I click on one of these posts it's going to load information about that post with a body a title as well as the person that wrote that if I click on their name I can see all the different posts that they have written now if I go back to my post page you can say I also have a paginated version of this so I can click the next and the previous Button as well as like an infinite scrolling version where I click this and load more button and I can constantly load more results in the bottom of the screen also you'll notice something really interesting this little like flowery kind of looking icon if I click on that and I'll just expand my page so it's easier to see and I'll move my camera out of the way for you for a second you can see here this is the dev tools essentially for the tan stack query and it's telling us all of the different queries that we're making on our page and it's giving us information on if they're stale if they're inactive if they're fresh if they're in the process of fetching and I can you know what Say Hey I want to refresh this and it's going to refetch that for me I can invalidate it if I want to I can reset it I can do a bunch of stuff like that so this is really good because it gives you Dev tools on what's going on so it's really easy to debug problems and as you can see I have tons of data on every single thing that's being returned here so now we can just close out of that real quick I'll get my screen back to how it was before and I'll move my camera back down and we can go through the actual code for how this works so the very first step to using tan stack query is you just need to wrap your application inside of a query client provider and you give it a query which in our case is just a brand new query client so it's nothing fancy we're just essentially doing the same thing you do with like react router so we're just wrapping our app like that and you can see here I have my Dev tools that I'm just appending on the end that's what's giving me this icon down here if I remove that you can see that our Dev tools are now removed it's just a nice quality of life feature to have when you're in development now I kind of want to go through the most simple example possible and this example is just a really simple post page this is the page you're looking at right here essentially if I go to my normal view this is the page you're looking at as you can see here we have this use Query function it's a custom hook part of tan stack query and this is where all of the magic of tan stack query happens so this use Query you give it a key and then you give it a function in our case this function is post when you pass a function to a query function it just needs to be any function that returns a promise if we just go to that function real quick you can see I'm using axios to make a git request to my API and I'm telling it to sort by title and it then it's just returning me a data which is just a list of all of our posts as you can see we have all of our posts being printed out here and they're ordered by title just like I would expect so super simple but I could replace this with something else I could just say return new promise and I could you know just give it some data inside of here so I could just say resolve I could just resolve with any data I want you know whatever it is and that's also going to return to it so let me just give it an empty erase this will actually render out something to the screen and now if I click save and I refresh you can see now I have an empty array so nothing's being printed out so it just has to be any type of Promise generally though it's going to be something like axios or fetch making a request for you so the other thing that's important about this is the query key so the idea behind react routers everything is based on these keys if I look inside of here you can see my key for this is that post that's showing up in my Dev tools and the key is just a unique identifier that says this is what this API route is so in our case I'm getting a list of all my posts so my key is just post and you can pass as many things as you want to these Keys anything it doesn't matter strings arrays objects it just needs to be something that is unique for that actual you know URL so in my case this is my post URL so I'm using post as my key and the really great thing about that is now it's going to Cache the results for that post in the background so if I ever go to another page that uses the same key it's just going to get the cache data and then refetch in the background for for me and show me the updated data when it's available so this is a really cool thing that this key right here this one simple line of code does all of my refetching and caching and validation for me that's where all the magic is happening now the other thing that's really cool about this is that we have all of our standard data being returned to us plus a bunch of other things you can see I have tons of information I can pull out of here if I want but the main things you're going to want is like a status the error as well as your data which in our case is our list of different posts so very standard stuff you would expect from any type of fetching related library and you'll notice if I inspect my page here and I'll just throttle my network so if I go to the network tab I can click that I want to throttle this to be a let's say a fast 3g connection so it's going to be a relatively slow when I refresh my page it's going to take a while for it to load and as soon as my react content downloads you should see the text loading up here on the screen and that's because right here if my status is loading it'll show the text loading and if there's an error I'll show the error so you saw that it said loading for a very brief second and then it actually loaded the content on the page let's remove that throttling for now and let's go to a slightly more complex example so what we can do is let's look at an individual post real quick you can see when I open this up we have information about the title the user of the post as well as the actual content of the post so if we go to our post component here you'll notice something really interesting we have our normal use Query right here which is getting all of our post related data and something else that's interesting is since this is a post on a particular ID you can see I'm using my query key as post to say that this is getting a post and then I'm passing out the actual ID that I'm querying so in our case 30 is the ID of this post right here and my function here is just getting the post you'll also notice I have a function that's getting the user information as well and that's because by default a post just has a user ID and I want to show the user's name so I first need to get my post and then once that's done I can get my actual user this is something that's normally pretty complicated to do with just a normal type of Fetch and use effect system but in our case with this is really easy so we have our first query here this is pretty much identical to what we had in our post here it's just a different key and a different function otherwise exactly the same the second one has an additional property passed to it called enabled though and what this property is saying is don't run this query until this returns true so in our case we're waiting until we get our post and we make sure that it has a user ID so we first download our post and then if that post has a user which it should then it's going to get the user for that post and return that information here I'm just checking to make sure everything's working fine so when we're loading our user here you can see I'm setting my username to loading in the case that it is currently being loaded so if I change this back to a slow 3g connection I just went over to my network change this to a slow 3g connection I'll go back to my all post I'm just going to click on a random post here well sorry that one was already loaded let's try it when we haven't loaded that like this one you can see it says loading because it's downloading the post and now you can see that it's waiting to download the user and then it printed out the user right there now if we wanted to show the text loading instead what I can do is I can just change this here to be something along the lines of user name there we go and now if I save and I go back to my post and just choose when we have it loaded you should see It'll say the text loading for us there you go it says loading it'll probably say the name twice but that's that's fine this is just for testing purposes so you can see that that's what's going on now you did notice that when I clicked on a post that I'd already downloaded it instantly loaded up the information for me that's something that's really nice about this library is because of these Keys I've already downloaded the information for post number 30. so instead of re-downloading that information again what it's going to do is it's going to show me the old version and then in the background it's going to re-download that information and then show me the new information we can actually see that happening inside of our Dev tools here so what I want to do is I just want to go back to all my posts and I'm going to click on that same post and you should see down here we look at this these are blue which means that it's refetching that data so it's showing me the old version of the cache data and then it's refetching the data in the background and if it's changed it's going to show me that new and updated information again super nice that this is all taken care of for you and really it's just a few lines of code I'm writing and it's doing all of that for me now that right there pretty much covers how you would actually do all your different fetching related stuff now what I want to do is talk about what happens when we want to create a post so I have this view right here for creating a post I pass it a title a body click create and it's going to create a post for me and I can show you if I just type in let's say a a b b b b and then we'll just give the body or actually it's just like one two three four there we go hit create we're still in the slow mode let me disable that so we don't have to worry about that we'll get rid of all the throttle and there we go so now you can see it's returned to us that post one two three four and it's given some body content into it and you can see that poster showing up right here super straightforward so what's happening the way to make this work is instead of doing a query you're using a mutation here A mutation is anytime you want to change data on your server so like a post or a put request for example you would use a mutation here and the only difference is the mutation just takes a mutation function which in our case is just a function that calls our API and passes along some information for what we want our post to be and then whenever this is successful you can use an on success or for example like an on-air in our case we're using an on success to say once this post has been successfully created what I want to do is navigate to that post using react router and then what I'm doing is I'm setting my data for my actual client now this is really important here because once I've actually created a post I have all my data for my post already so instead of going to the post page and then refetching that data instead what I'm telling tan stack query is what I want you to do is I want you to Cache that information using this key so it's the same key we would use over here post and then ID so I'm using that post ID key so now when I try to access this new post that I just created it's just going to get the data from the cache I'll show you exactly what that looks like first what I'm going to do is I'm going to throttle my network so come in here we'll turn us down to slow 3G create post type in our title which is just going to be two three four five random body text I'm going to comment out this line so it's not going to do that saving of the cache so when I click right here it's going to load and that's it actually creating the post now we're on the post page and now it's having to refetch that data you saw we had two sets of loading let me bring that line back in and go back to create a brand new post three four five blah blah blah blah blah hit create and we're loading that's creating the post and then as soon as that's done it instantly brings us to this page and that again is because it's already been cached so it's showing us the cached information and then refetching in the background for us you'll also notice this in effect if we go back to all post page you'll notice we don't have that post yet but now you can see it just popped up on the screen that's because it was showing us the old cache version of our all post and then in the background it's downloading the new data and showing it to us I'll show that again I'll do one called 444 and you can see when we go back to all posts you'll notice that that is not in our list you can see it's not right here but after a little bit that appears because it is fetched in the background this is super cool and I love that this is all handled for you also for for this mutate all that you need to do to make this work is it returns to a mutate function and this mutate function is what you call and that mutate function is essentially whatever you pass right here so it's just taking that function that you pass into here and it's returning it to you right here for you to call it a later time now the final two things I want to talk about are pagination and infinite scrolling I don't want to go super deep into them I just want to show you that they're possible and relatively easy to do so for our paginated route you can see if I remove our throttling because it's quite slow you can see that we can click this next and this previous button to go next and previous and all we're doing right here is we're giving it a query key where we're passing in an object with the value of our page as the actual key here and then our function is just calling git post paginated and all this does is taken a page and do some pagination for us pretty straightforward stuff so it's super simple pagination works pretty much exactly the same as normal fetching the only key here is you pass this keep previous data true and that's just going to make sure your old data stays on the screen until the new data is loaded if I remove this and I do my throttling again so I just throttled our connection I click next let me just refresh here real quick so we have our cache completely wiped for us so that'll just take a second here let me remove the throttling put it back on there we go so if I click next you're going to see all of our data disappears and then it's going to reappear this line of code right here is just making sure that doesn't happen so now when I click next you can see that it's doing this all fine and you can see it says loading at the top here and that's because I can just check my fetching status so the really cool thing about react query or tan stat query is it has two different statuses you have a normal status of like finished loading and loading and then you have a fetching status for every time it refetches data so it's really easy to know whether or not you're in the first load or a refetch in our case now infinite scrolling is very similar but you use a different function called use infinite query and this is a little bit more complex because you need to patch it a few more properties for like determining how you can get the next piece of data so like when I scroll down and I click my load more button here it needs to know what the actual data is that it's trying to load and what page you're on a little bit more complex but overall it's fairly simple and it gives you features like infinite scrolling such as this and that's all there is to tan stack query I hope you're as excited about this Library as I am and if you are you're definitely going to want to check out my full tutorial which I'll have linked right over here as soon as I finish creating it with that said thank you very much for watching and have a good day

Original Description

I absolutely love React Query, also known as TanStack Query. This library singlehandedly makes working in React so much nicer and I can’t imagine creating a large scale project without it. In this video I will show you what React Query is, what it can do, and demo all of that in an application. 📚 Materials/References: React Query Crash Course: https://youtu.be/r8Dg0KVnfMA 🌎 Find Me Here: My Blog: https://blog.webdevsimplified.com My Courses: https://courses.webdevsimplified.com Patreon: https://www.patreon.com/WebDevSimplified Twitter: https://twitter.com/DevSimplified Discord: https://discord.gg/7StTjnR GitHub: https://github.com/WebDevSimplified CodePen: https://codepen.io/WebDevSimplified ⏱️ Timestamps: 00:00 - Introduction 00:38 - TanStack Query Overview 01:17 - Project Overview 02:41 - useQuery Basics 09:00 - useMutation Basics 11:54 - Pagination 13:18 - Infinite Scrolling #ReactQuery #WDS #TanStackQuery
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Web Dev Simplified · Web Dev Simplified · 0 of 60

← Previous Next →
1 Introduction to Web Development || Setup || Part 1
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
2 Introduction to Web Development || Understanding the Web || Part 2
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
3 Introduction to HTML || Your First Web Page || Part 1
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
4 Introduction to HTML || Basic HTML Elements || Part 2
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
5 Introduction to HTML || Advanced HTML Elements || Part 3
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
6 Introduction to HTML || Links and Inputs || Part 4
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
7 Learn Git in 20 Minutes
Learn Git in 20 Minutes
Web Dev Simplified
8 5 Must Know Sites For Web Developers
5 Must Know Sites For Web Developers
Web Dev Simplified
9 10 Best Visual Studio Code Extensions
10 Best Visual Studio Code Extensions
Web Dev Simplified
10 Learn CSS in 20 Minutes
Learn CSS in 20 Minutes
Web Dev Simplified
11 How to Style a Modern Website (Part One)
How to Style a Modern Website (Part One)
Web Dev Simplified
12 How to Style a Modern Website (Part Two)
How to Style a Modern Website (Part Two)
Web Dev Simplified
13 3D Flip Button Tutorial
3D Flip Button Tutorial
Web Dev Simplified
14 How to Style a Modern Website (Part Three)
How to Style a Modern Website (Part Three)
Web Dev Simplified
15 Animated Loading Spinner Tutorial
Animated Loading Spinner Tutorial
Web Dev Simplified
16 How to Write the Perfect Developer Resume
How to Write the Perfect Developer Resume
Web Dev Simplified
17 Animated Text Reveal Tutorial
Animated Text Reveal Tutorial
Web Dev Simplified
18 Learn Flexbox in 15 Minutes
Learn Flexbox in 15 Minutes
Web Dev Simplified
19 Custom Checkbox Tutorial
Custom Checkbox Tutorial
Web Dev Simplified
20 Start Contributing to Open Source (Hacktoberfest)
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
21 JavaScript Shopping Cart Tutorial for Beginners
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
22 Responsive Video Background Tutorial
Responsive Video Background Tutorial
Web Dev Simplified
23 1,000 Subscriber Giveaway
1,000 Subscriber Giveaway
Web Dev Simplified
24 How To Prevent The Most Common Cross Site Scripting Attack
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
25 Transparent Login Form Tutorial
Transparent Login Form Tutorial
Web Dev Simplified
26 The Forgotten CSS Position
The Forgotten CSS Position
Web Dev Simplified
27 How to Code a Card Matching Game
How to Code a Card Matching Game
Web Dev Simplified
28 10 Must Install Visual Studio Code Extensions
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
29 Learn CSS Grid in 20 Minutes
Learn CSS Grid in 20 Minutes
Web Dev Simplified
30 Learn JSON in 10 Minutes
Learn JSON in 10 Minutes
Web Dev Simplified
31 10 Essential Keyboard Shortcuts For Programmers
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
32 What Is The Fastest Way To Load JavaScript
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
33 Differences Between Var, Let, and Const
Differences Between Var, Let, and Const
Web Dev Simplified
34 How To Install MySQL (Server and Workbench)
How To Install MySQL (Server and Workbench)
Web Dev Simplified
35 Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
Web Dev Simplified
36 How To Solve SQL Problems
How To Solve SQL Problems
Web Dev Simplified
37 What Are Design Patterns?
What Are Design Patterns?
Web Dev Simplified
38 Null Object Pattern - Design Patterns
Null Object Pattern - Design Patterns
Web Dev Simplified
39 Your First Node.js Web Server
Your First Node.js Web Server
Web Dev Simplified
40 How To Setup Payments With Node.js And Stripe
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
41 How To Learn Any New Programming Skill Fast
How To Learn Any New Programming Skill Fast
Web Dev Simplified
42 Asynchronous Vs Synchronous Programming
Asynchronous Vs Synchronous Programming
Web Dev Simplified
43 JavaScript ES6 Arrow Functions Tutorial
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
44 Are You Too Old To Learn Programming?
Are You Too Old To Learn Programming?
Web Dev Simplified
45 JavaScript Cookies vs Local Storage vs Session Storage
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
46 JavaScript Promises In 10 Minutes
JavaScript Promises In 10 Minutes
Web Dev Simplified
47 Builder Pattern - Design Patterns
Builder Pattern - Design Patterns
Web Dev Simplified
48 JavaScript == VS ===
JavaScript == VS ===
Web Dev Simplified
49 JavaScript ES6 Modules
JavaScript ES6 Modules
Web Dev Simplified
50 8 Must Know JavaScript Array Methods
8 Must Know JavaScript Array Methods
Web Dev Simplified
51 CSS Variables Tutorial
CSS Variables Tutorial
Web Dev Simplified
52 JavaScript Async Await
JavaScript Async Await
Web Dev Simplified
53 How To Choose Your First Programming Language
How To Choose Your First Programming Language
Web Dev Simplified
54 Easiest Way To Work With Web Fonts
Easiest Way To Work With Web Fonts
Web Dev Simplified
55 Singleton Pattern - Design Patterns
Singleton Pattern - Design Patterns
Web Dev Simplified
56 Responsive Navbar Tutorial
Responsive Navbar Tutorial
Web Dev Simplified
57 CSS Progress Bar Tutorial
CSS Progress Bar Tutorial
Web Dev Simplified
58 Learn GraphQL In 40 Minutes
Learn GraphQL In 40 Minutes
Web Dev Simplified
59 What is an API?
What is an API?
Web Dev Simplified
60 Learn How To Build A Website In 1 Hour!
Learn How To Build A Website In 1 Hour!
Web Dev Simplified

This video teaches how to use React Query to simplify writing React code by handling caching, cache validation, and refetching, and demonstrates its features and usage in various examples. React Query provides a simple and efficient way to manage data fetching and caching in React applications. By using React Query, developers can write more efficient and scalable code.

Key Takeaways
  1. Wrap application with Query Client Provider
  2. Use Query function with key and function that returns a promise
  3. Pass function to Query function that returns a promise
  4. Use Axios to make a GET request to API
  5. Sort data by title
  6. Set a query key to identify the type of data being fetched
  7. Use the enabled property to conditionally run a query based on the result of another query
  8. Handle loading and error states for the user data
  9. Use React Query to cache data for posts
  10. Use mutations to create new posts
💡 React Query provides a simple and efficient way to manage data fetching and caching in React applications, making it a valuable tool for developers.

Related Reads

📰
I Spent a Week Trying to Break an AI. The Hard Part Wasn’t Breaking It.
Learn how to build a prompt injection attack on an AI model and understand the challenges of measuring success in AI security testing
Medium · Machine Learning
📰
Everyone Is Chasing AI Benchmarks, Almost Nobody Is Measuring Truth
The AI community is overly focused on benchmarks, neglecting the importance of measuring truth and real-world impact, which is crucial for building practical AI solutions.
Hackernoon
📰
Politeness Is Not a Security Model — Hooks & MCP in Claude Code, Deep Dive Part 5
Learn how to secure your AI models using deterministic guardrails and a universal adapter, connecting them to tools like Figma and GitHub
Medium · Programming
📰
Kan AI blive bevidst? Tre eksperter mødtes – og blev ikke enige
Experts discuss whether AI can become conscious, but fail to reach a consensus, highlighting the complexity of the issue
Dev.to AI

Chapters (7)

Introduction
0:38 TanStack Query Overview
1:17 Project Overview
2:41 useQuery Basics
9:00 useMutation Basics
11:54 Pagination
13:18 Infinite Scrolling
Up next
Anthropic warns About This AI could escape control!
PlivoAI
Watch →