The Better Way to do Loading States in React

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
there's a really neat trick that you can use in your react applications to make them feel instant to users and that trick is called optimistic updates an optimistic update like the name my suggest means that whatever action a user is performing liking something writing a comment you're instantly showing the success state so the like will immediately be there the comment will immediately be shown on the screen and this technique this trick of optimistic updates is super widespread in the Enterprise World in any good software like Discord for example if you write a message there is no loading State instead the message is right away put into the chat window and that's the beauty of optimistic updates these three techniques are what I can think of to properly Implement optimistic updates in your react app let me show you why I'm not a fan of the first two and then the third one which I always use in my personal apps approach number one is literally doing everything yourself and you'll see why this approach might not be ideal as an example let's use a like counter where when you like for example this video the like will be updated immediately afterwards let's give it the button that's going to be the thumbs up icon for example below this video that you could press if you like this video and when clicking this button the like should show up instantly in order to achieve this let's also add a loading state that we default the falce and just do some conditional jsx and all of the interesting Logic for the optimistic update happens in the handle like click function so let's take a look at that function in closer detail where the first thing we do is optimistically update the state because we assume that the API will not have any errors so let's instantly increment the likes afterwards we want to do the actual database call and the arrow handling and of course we're going to do that inside of a TR catch block where the response is simply a mocked API call this would be your call to the database for example to increment the likes for this video by One the API data looks just like this with a success property and a total likes property if everything went smoothly if the response was successful let's set the likes to the fresh database data we just got or else we're going to revert it back to the original likes and same thing if anything went wrong in that case we're going to set the likes to the initial likes that we had and finally we're just going to disable the loading State and that's all we need to do to achieve proper optimistic updates in plain react with doing everything ourself and yes this works let's try mocking an error for example with the reject property in or mocked API call let's reject this with a success of false after 1 second so let's say your database just can't handle this operation at this time let's press the like button the optimistic update will still happen but then the original likes the two is going to be restored and this works beautifully but just for now because as your app complexity grows so will this approach of optimistic updates keeping track of everything yourself in state can get very confusing very fast and this is literally the most simple example let's take a look at approach number two and this is one I straight up could not get to work at all some people talk about this experimental use optimistic hook that react has introduced for me it literally doesn't work in theory what should happen is that you keep track of two states and you pass in the actual State into the use optimistic and when you want to perform an optimistic update you can simply set the optimistic version of that state that is displayed in your jsx to the user to immediately reflect the changes and then you make an API call that's the exact same thing which when it's done is going to update the actual state to get the fresh datab Bas data into your UI and even if it did work and didn't throw an error each time I try this out you probably wouldn't really want experimental stuff in your app that has a lot of users anyways right so let's take a look at a much more foundational much more solid example let's go back to the original repo and that is using react query don't worry if you've never used react query I'm going to walk you through every step of how this works why this works and why it's so interesting so let's start with a fetcher function and that's a use Query the only thing this does is make a get request whenever this component this react query. TSX component is rendered and what is this going to do first off we're going to give it a query key this is going to be important for later and we're going to give it a query function this would be a fetch function to your database however I'm just marking a database response that is a likes equals zero now let's check out what happens when the user clicks the like button that we have right down here by the way it's the exact same jsx however some values are still not defined we're going to walk through every step to make a request to our back end to update the like State this is what the mutate is for that we can destructure from react queries use mutation which is nothing else than like we're making a post request to our back end and the logic for this used mutation happens inside of the mutation function where we can make a mocked API call for example to increment the like in the database by one and we're going to get back the response in our example this is just going to be a type success and a total likes just the same as before nothing has changed there and now as to how we do the optimistic Updates this is the interesting part that you're here for this happens in the on mutate a callback function that gets called as soon as this mutation is called which is called as soon as we click this button so immediately after pressing this button this callback will be executed first off let's cancel all outgoing queries that are made by this function up here that's what the query key is for we can cancel all queries with that query key essentially just this function right here because they could overwrite our optimistic updates if we did not cancel them like this afterwards let's get the current data that we can then pass into the on eror call back later if something should goes wrong so we can restore the original state if anything goes wrong and then let's do our optimistic updates by setting the query data to whatever we want to optimistically update in our case we want to increase increment the likes by one and simply returning the previous likes just like this so we can then restore them in the on error if anything goes wrong let's set the query data back to the previous lik so nothing ever happened your like won't be counted if our API route failed for some reason and then we're going to use an unsettled callback this will be executed whether we are successful or not whether there is an error or not it doesn't matter this unsettled will be run and in here we can refresh the data and show the current database State the most fresh version of our likes and that is literally all we need to do with react query if you've never worked with it it might seem a bit more abstract but let me show you that this works let's go into our main. TSX this is just a v project and let's import the react query like counter get rid of all the unused Imports by pressing shift alt and all save this file and let's go back into our demo project reload this and see what happens in the react query version let's hit like that's going to update it if we click like again that's going to update it however one thing I implemented is that if we look into the console and then the source code you will see that there is a 30% chance of this API being rejected right here so as we press this eventually we should see an error pop up in the console and there should be some correct error handling for this let's press it again and there it was there was the random API error that we wanted to throw and as you can see the original state was immediately restored back to two and these intuitive callbacks with the on mutate and on error is why I find react query much more manageable for this especially if you know that your app is going to grow in code complexity as to compare to something like literally keeping track of everything yourself in plain react hey I really hope you enjoyed this video and now understand what an optimistic update is and why it's so useful to implement in your own apps because the bottom line is it makes your app feel so fast even though you literally didn't change anything about the API you just have improved arrrow handling and it feels so much faster to the users if you want to know a really nice typescript trick for conditionals check out this video it's going to be super useful in your next app and I'm going to see you in the next video Until then have a good one and bye-bye
Info
Channel: Josh tried coding
Views: 76,716
Rating: undefined out of 5
Keywords: react, reactjs, loading state, optimistic update, react optimistic updates, react optimistic update, react query optimistic, react query optimistic update, useoptimistic, react useoptimistic, react experimental useoptimistic, tanstack query, react query, optimistic, update, nextjs, typescript, josh tried coding, joshtriedcoding
Id: V0VfR0eaz98
Channel Id: undefined
Length: 8min 18sec (498 seconds)
Published: Sun Oct 08 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.