Skip to main content
View on YouTube to comment and like!

Syntax Video

React vs Vue - Async State, Effects and Custom Hooks

Chapter 1 0:00

Intro

ah the dreaded loading spinner the bane of every user's existence but a necessity in a world where things are not instant and when you're building front-end applications you typically have to deal with asynchronous things that is requests to apis or servers or whatever else and in this video I'm going to show how we can handle async state in both View and react now this is the third video in a multipart series where I'm comparing the same apps built with View and react and like I said this video is all about async State and this basic example I have for you is just hitting API waiting for the response displaying out the results and it's also paginated so the user can actually page to the results I also have a slightly more advanced example for you that deals with some of the other things you might come across in the real world like slow requests and also the API returning errors so in this example the API returns an error 40% of the time so let's see if we can get it to trigger an error so you can search for something get back the results but if uh every now and then yeah it makes it comes back with an error now in the real world you

Chapter 2 0:27

What will we build?

might actually retry this request behind the scenes in this example I just want to show that error to the user and then give them a button so that they can retry again and again now another thing you typically deal with is uh managing multiple async requests and making sure that the UI stays up to date now this is really airing out come on come on um and uh what I mean by that is let's say the user clicks next to go to the next page but then clicks next again before that page is loaded like this what do you do because if you don't cancel that previous request it's possible that the previous request resolves after the current request and then you're Pages out of sync and so in this example I'll show you how we can cancel requests in flight and manage that on the front end as well so let's dive in my name is CJ welcome to [Music] syntax first let's take a look at how I implemented this with react now you can see here I have the image search component and then lots of State variables the first state variable here is input

Chapter 3 1:51

React Image Search / useEffect

and we are just keeping track of what the user has typed in on that state variable now I have a separate State variable for search term because essentially whenever the form is submitted that's when I want to make the API request so that's when I set the search term value so here on the form when it's submitted we call our onsubmit function and inside of here I reset all of my state variables that matter and then specifically set the search term State value and that in turn fires off this use effect so use effect is how we manage asynchronous things inside of react and essentially you pass in a dependency array and when any one of those dependencies change this function will rerun that we pass in here and so in this case I'm using that to my advantage when the form is submitted I'm just updating those State variables and behind the scenes this use effect is going to rerun inside the use effect we reset a few more State variables we reach out to our API and then that API responds with an object that has some metadata like the total number of results and the amount per page and then also the photos themselves so we use use

that data to calculate how many total Pages they are update our state with that list of photos and then we're good to go at that point our page should reender and if we look at our render function we have a place where we're showing that loading image and then we also have a place where we're iterating over those images and then also showing a message if there were no images at all now if we take a look at the next and previous buttons they are essentially just setting the next page that's all they have to do because of the use effect right so when we press the previous button we take the current page and subtract one when we press the next button we take the current page and add one and because we're updating that state variable our use effect up here is going to rerun because it's dependent on that state variable so in the react example here really the main thing to pay attention for async state is this use effect here and you will notice that I have to wrap my code that uses async O8 in an iffy or an immediately invoked function expression because use effect cannot accept an async function you'll see if I pass in an async function I'm getting a type error and that's because a use effect can return a function so

Chapter 4 3:39

React useEffect dispose function

this returned function Here is known as our disposal function and essentially if this use effect ever needs to be recall that is its dependencies change this function will run so you can dispose of things or change things up in this example I'm not disposing of anything so I'm not actually returning a function but I do have to wrap my code here in an iffy if I want to use a syn8 now let's take a look at how I implemented this with view so up at the top of my component you can see here I have all these State variables again we have both input and search term if we look at our template input is bound to that input there and uh whenever that changes that's getting updated behind the scenes but whenever we submit the form we call our onsubmit function and inside of here we check to make sure the user has actually entered something in reset a few State variables and then actually set our search term value there now inside of view we have this function called watch and watch allows you to pass in some reactive variables or a getter function that returns some value

Chapter 5 4:21

Vue Image Search / watch

and if its dependency ever change here the function that you pass in second will get recalled and so that's how we're managing things here inside of view if search term or page ever change this function is going to get reined and here it's very straightforward we just reset some State variables call our API and then update the page accordingly now if we look at the template we can see how we're using these State variables first up we have that loading image so if loading is true that loading image is going to show and then here is where we iterate over all of our images and render out each image and then we also have our message down here if there were no results from the API now if we take a look at the next and previous buttons they essentially just modify that page State variable directly right so when the next button is pressed increase Page by one when the previous button is pressed decrease Page by one and because it's modifying those State variables this Watcher is going to see that and then rerun our function here when they change now on the surface both of these examples are fairly similar but there are some caveats when using use effect in react so let's take a look at use effect in react versus watch inside of

Chapter 6 5:48

React useEffect gotchas

view now in react here let's actually see what happens if I navigate away from the image search page and then back we actually see a flash of loading State and you can see that API requests were made and that's because in react a use effect is going to run the first time whenever a component mounts so that's just the the default behavior of use effect you can't change that essentially when this component mounts this use effect is going to run with the initial values of both search term and page and so that's why we're actually seeing the loading State flashed to true it's because this use effect is actually running when the page mounts now another thing you might have noticed is that it made two API requests now this has to do with react strict mode and uh there also is not much you can do about that and so here in my react app if we look how it's mounted we're using strict mode and so this was introduced I think in react 14 and essentially uh it mounts your your app and your components twice and you need to make sure to take that into account now for this example um I think probably the easiest way to make sure that we don't fire off two requests in

quick succession is potentially wrap this in some kind of set timeout so we for instance could have a timeout here and then we'll call a set timeout and uh I'm pretty sure this can be immediate and then we can actually just move this whole function inside that set timeout like this and then we can actually return a disposal function so if we return a disposal function that calls clear timeout with that timeout and so now if this use effect is ever called in quick succession the previous one will be canceled and so this should get rid of our double request so if I refresh the page here we do only see a sing single request uh but now we still are seeing an API request and I don't actually want to call the API whenever the page loads so probably the easiest way to fix it in this example is to probably just check to see if the search term value is set here inside of this use effect another thing you could do is potentially create a ref that is how many times this component is rendered and if the ref is greater than one actually allow list to be called uh but for this specific example probably the

easiest thing to do is just say uh if the SE term is actually set or if it's not set then don't do anything uh so that would prevent that API request from happening when the page loads but we should be good to go for all other types of requests like that great uh but in view we don't have to think about these these same types of things so by default watch does not get called when the component mounts it only gets called when these dependencies change if we want this to be called when the component is created there are some options for that so watch actually allows you to pass in some options here and you can say immediate true and so this will give you the similar Behavior where when the component is created this function is called uh but it's nice that we can actually like opt into that if we want to the other thing is inside of react we typically use use effect as kind of like our component did Mount if you remember the days of like class components so a lot of times in react you might have a use effect and then that just has an empty dependency array and you kind of treat this as your like component did mounts because you expect that this is only going to run once

Chapter 7 8:11

Vue watch options / immediate

Chapter 8 8:36

React useEffect / component mount

because it has no dependencies inside a view there is a specific method for that so here there's a method called on mounted and you can explicitly opt into when the component mounts and so in view you typically reach for the specific function depending on what you want to do so here I can pass in a function to on mounted and then do the things I want to do when the component mounts and so this is one of the things I like about Vue is you can be very explicit about how you're watching for variables and how your functions rerun whereas in react is kind of All or Nothing essentially all we have is use effect and we need to think about all the various scenarios where that use effect might rerun or prevent it from uh running on Mount and so those are a lot of the things you do have to take into account when you're using use effect in react so that's it for the simple image search let's take a look at this Advanced image search so you might have noticed in the previous example I was not accounting for errors so if the API errored out the UI probably would have just crashed but in this example I'm accounting for errors so the API that we're calling here responds with an

Chapter 9 8:56

Vue onMounted

Chapter 10 9:14

Vue vs React - Lifecycle

Chapter 12 10:21

React custom hook

function is exactly the same the only difference is we've kind of extracted out that logic and then from that Hook expose the specific things that this component needs so let's take a look at that custom hook use images so this accepts the search term and the page and inside of it is where we have all of the associated State variables and then also effects and this custom Hook is basically returning everything that needs to be usable by the outside world now for this example like I showed I wanted that try again button to be able to refire off the request and so that's why in this custom hook I actually am exposing fetch images to the outside world because inside of the component that try again button needs to be able to fire off fetching of the images if there was an error and so that's why I've structured the code in this way and essentially what I've done is I've defined fetch images using use callback so use callback is from react and it allows us to Define functions that will only get redeclared if their dependencies change so it's very similar to use effect but specifically for

defining callbacks or functions and in this case I only want fetch images to be recreated if page or search term change so those are its dependencies and then to get the behavior of actually firing off that request when those dependencies change I have a separate use effect so this use effect is dependent on fetch images so if fetch images changes that means that page or search term changed and if that's the case we want to refire off fetch images so in this example because I wanted that behavior of being able to call fetch images outside of this hook I structured it this way so we can actually expose fetch images to the outside world now here it's important that I wrap this inside of used callback because a react component is going to reinvoke all of these used functions every time the component is rendered I need to make sure that use images doesn't return a brand new fetch images function every time it only returns a new one if page or search term have changed so that's the basics of this custom hook here we also need to handle cancelling requests but before we dive into that let's take a look at how we implemented a similar reusable function inside of view so here's our component

Chapter 13 12:41

Vue custom hook

very similar again we just have our state variables here but we've wrapped up all of that functionality into this reusable function here called use images and use images accepts both the search term and the page and then gives us back a few things that we can use inside of our render function and again I want to be able to expose fetch images because if there was an error I need a button that will let the user refetch those images so let's take a look at how I implemented that use images hook so over here I'm exporting that function and I'm taking in search term and page but you'll notice in view here I am making sure that these are actually refs so because I want to see when those values change I need to make sure that I actually get the reactive value and so we Define them as refs over here and then inside of this custom hook here I'll know when they change I can use like the watch function and stuff like that so if we look inside I've got some State variables then I've got my fetch images function and in this case I want to recall fetch images if search term or page change and then to expose this

function and state variables I'm just returning an object and that way inside of the component I can actually pull those off and then use them inside of the render function so that's how we create reusable functions in both View and react now let let take a look at how I'm handling that error State and also how I'm cancelling inlight requests so there is this thing called abort controller and you can create this and pass in its signal to a fetch request and if that fetch request needs to be canceled for some reason you can use the abort controller so let's take a look at pagination here so if I click next that'll start loading the next page but if I click next again that'll load the page after that and I want to cancel the request for the previous page so I'll click next and then click next again you'll notice that behind the scenes that request got canceled now it AED out but that's besides the point of cancellation essentially make the request cancel the previous one if it sees a new request come in while that request is in flight because if I click next and then the request for a previous

Chapter 14 13:58

AbortController / canceling requests

page was still in Flight if it's not cancelled then it's going to update the state when that request comes back and then we could be out of sync right because I could be loading this page it loads a previous page and then all of a sudden I'm seeing the results for this page or in the worst case the the results for previous page load after the results for the current page load so it's important that you cancel those inflight requests let's take a look at how we do this inside of react so like I said we have that abort controller now here inside of react I'm using a ref so a ref in react allows you to modify its current value without triggering a render so for usate we have this Setter function and we call that and that's going to trigger a re-render but with a ref we just have the current value and we can just set it and not trigger a render and that's important because in here inside of fetch images we are setting the abort controller when we fire off that request and if we were using use State this call back would have to be dependent on it but then we're updating it inside of this call back and it would cause an infinite Loop so I'm using a ref that ref starts off

Chapter 15 15:04

React abortController / useRef

as null inside of this function we abort the previous requests so if fetch images gets called again and there was an inflight request we're going to grab the current abort controller and call the abort method now of course it could be null because it's possible this is the first time we're firing this off so I need to make sure I only invoke abort if the current value is actually set now all of our state updates are the same however this API function that calls to get images now needs to return two things it needs to expose that abort controller that it's passing under the hood to fetch and then also expose the response which is going to resolve to the results from that API request so in this case we get back both the controller and the response and I'm updating the ref here so I'm grabbing a boort controller grabbing its current one and then setting it to this specific specific ones so each time we fire off a requests we're updating a boort controller to be the current one uh for the current request after that we await the response and then update our state variables but we need to also handle the error here so we've wrapped the await for that specific API response in a tri

catch and if it throws an error we need to update the error message however if it was an abort error we don't want to show an error message right we don't want to show the user that the previous request was aborted we're just doing that behind the scenes so if there was some kind of error meaning the API errored out we want to grabb the message that the API responded with set that on State and so that way we can show the error message to the user now the other spot where I am calling abort is inside of this use effect now technically if I only cared about this page I wouldn't have to return a disposal function because we are calling abort here but we're treating this as our component did unmount so if we navigate away from this page and there was a request in progress we want to abort it and so that's the main reason I have this disposal function so for examp example if I click next and then navigate away we cancel that request because I'm not on that page anymore so I don't need to worry about the response from that request so this cancellation of requests actually works for multiple scenarios not just pagination so let's say a user types in

a search term and then immediately types in a new search term we want to cancel the request for the previous search term and then this one errored out so we're showing that error message but we can try again with that search

term there we go but again we want the same behavior if the user is paginating right so if they're if they're navigating to different pages we want to cancel those previous requests I probably should not have made this API error out as much as it does okay but that's that's the react example now let's take a look at cancellation and air handling here inside of you first up we have our abort controller variable you'll notice it's just a variable I don't have to W wrap it in ref or anything like that because I don't need to watch it for changes and essentially I just need the latest value and one of the nice things about View is these hook functions don't get called over and over again they're only going to get called once when the component is created which means I'm only going to get one variable when the component is created and then here inside of fetch images I can check to see is it null if it's not call abort update our state variables and then again we have this Handler that comes back from get images which gives us the abort controller and the response promise here I'm just going to reassign the controller so that way every time this function gets called up

Chapter 16 18:13

Vue AbortController

at the top I'm always aboring the latest request will await that response we have it wrapped in a tri catch so if it errors out and it was not an abort error we will set that error on State and display the error to the user now this is one of the nice things about View and it on the surface you may not realize this but all of this code that's defined here at the top of my function only runs once when the component is created so even this invocation of use images that only gets called once which means I can just have regular variables inside of here and I don't have to worry about keeping track of what the current or latest one is like I do inside of react so over here and react we did use this used ref because I want to keep track of the same one on renders and all of this stuff gets recalled again so I need to make sure that I always have access to the correct current value so in view we don't have to worry about that we can just use the variable itself now to handle cancellation whenever the user navigates away we just use on unmounted so this is a built-in function here inside of you and you can call it even outside of components but because this function was invoked in the context of a component on unmounted is going to get

Chapter 17 19:07

Vue script only gets called once

Chapter 18 19:29

React hooks get called every render

Chapter 19 19:42

Vue onUnmounted

fired when that component is unmounted and so here I can just say controller. boort whenever we navigate away from this page so if we look at the view example I can make a search but if I navigate away that request gets cancelled so that's it for this comparison now I touched on these things earlier but to really sum up the major differences and kind of why I prefer the view way of doing it is that use effect inside of react is multi-purpose right it's component did Mount component did unmount it's a watcher for dependency changes it's a single thing used for a lot of different things and you need to make sure that you're using it in the right way now inside of view we have purpose-built functions to do these things that we do often right so we have watch so we can reinvoke a function if some dependencies change we have on unmounted to run some code when a component unmounts we have on mounted to run some code when a component does Mount we also have some options that we can pass into watch right so we can actually opt into running this thing immediately versus running immediately by default and ultimately when we're reading our code it's much more explicit about when this stuff will run now in

Chapter 20 20:07

Final Thoughts

react you really have to read these functions to understand what their purpose is right and if you're in a large code base and you come across a component and you see a use effect you don't immediately know is this a component did Mount component did unmount what is this for you actually have to analyze the code to understand better specifically what this use effect is for and so for me that's the major thing that makes it harder to work inside of react code bases is really just trying to understand each of these use effects because every single one is potentially different now if you enjoyed this be sure to subscribe click that notification Bell so you can be alerted whenever I drop the last video in this series which is this stocks example so this is a little stock dashboard it allows you to add some symbols reaches out to the Yahoo finance API and then updates the price in real time as it receives those updates from the Yahoo finance API so you can add as many symbols as you want and then each one is going to have its own unique chart and this is really an example of a highly interactive front end that has lots of asynchronous State updates and and lots

Chapter 21 21:23

Next Time

of nested components and different things like that thank you so much for watching if you have any questions or comments about the code that I showed you today leave a comment down below and if you have any concerns or you think maybe you can implement the react example in a better way let me know in the comments and also this code is completely open source so check the link in the description feel free to open an issue or something like that if you think some of the stuff that I have done could be improved in any way all right I'll see you in the next one [Music]

Chapter 22 21:55

Thanks!

Quote it with credit and a link. Quoting Syntax