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

Syntax Video

Clean Up React Code with useReducer | Code Renovation

Chapter 1 0:00

intro

welcome to code renovation in this video we are going to do some renovation of some slightly messy react code now for this example I'm actually refactoring some code that I wrote in a previous video so if you're interested to see me actually write the code you can check out the video called use fetch from scratch but essentially we implemented a custom react hook this allows the users of our hook to pass in a custom type in a URL and our hook will make a fetch request off to that URL and handle all of the internal state so it handles things like whether or not it's loading setting the error and then also provides the data once that fetch is completed and so in this video we're going to take this custom hook which has several use States and refactor it into a reducer and so if you've never used reducers before that's okay we're going to talk about what they are we're going to build this from the ground up to kind of get you used to working with reducers but I'll show and talk about why this is potentially a good refactor especially for scenarios where you're using lots of use States and so in this video we're

going to take this slightly messy code and refactor it into something that's a little bit nicer so if that sounds good to you let's clean this code up my name is CJ welcome to syntax now if you'd like to follow along you can watch the previous video where I wrote this Hook from scratch but if you don't want to do that you can go ahead and clone the repo down so the link to this will be in the description you can head to the use fetch folder now I started by just copying my existing solution and adding reducer on there so that way the previous solution will still be there if you want to look at it but the new solution will be in a file called reducer dos solution uh the other thing is I want all of my tests to run and Right Now the default test file has all of the tests as optional so I just copied the tests over imported from my reducer solution and then enabled all of the tests and so from there I have a fully passing test suite and whenever you're doing a refactor this is a really good thing to have because this refactor shouldn't break anything this refactor should allow the code to work exactly the same as before the only things that are changing is how we're actually working with that internal state so we want to start by making sure that our

Chapter 2 1:12

code setup

full test Suite passes and then start making our refactors from there and with each new thing that we change the tests should continue passing now typically when you see a custom hook or a component that has probably more than three used State hooks it's probably a good use case for Ed reducer the other spot that you want to look at is in your code that actually updates your state are you calling multiple State updaters all in a row and if that's the case this is a really good indicator that you could benefit from using a reducer because basically what we can do is we can describe this specific specific State transition right we're we're updating all of these State variables one after another but really what are we doing here and in this case we're either ending the request or starting the request and then similarly down here we we update a bunch of State variables so we're either ending the request with some data or ending the request with no data and an error message and so instead of having all of these individual State updates we can group it into something that has a specific name on it now I want to start small so we can really see what this use reducer is doing and for

Chapter 3 2:05

when should we use a reducer?

Chapter 4 2:52

convert a single useState to a useReducer

that I'm actually just going to convert this use State into a use reducer and so our custom hook has a URL value and then it has an updater function that it exposes to the world so it uses the URL to know where to make the request to and then to the outside world it exposes this update URL function so that the consumer of our hook can actually change the url but we don't actually call update URL uh in any of our code that's only called by the outside world so this is going to be a pretty simple refactor um but you're going to see kind of how a reducer works so first up we need a function that is a reducer reducer is just a function so we'll create a function called use fetch reducer and the idea with the reducer is it takes in the current state and then Returns the next state so we need a type that describes the state for this particular reducer now we already have a return value here that kind of describes all the things internally and this type needs to stay the same for the most part but I am going to extract out the things that my reducer is going to be in charge of and then kind of like share that type across it and so the thing that we're refactoring right now is the URL so I'm

Chapter 5 3:26

create a reducer function

Chapter 6 3:38

create a state type for our reducer

actually going to create another type called use fetch base State and I'm going to pull that URL into that base State and then that now will break the types because uh the return value here includes that URL so to fix it we'll make sure that the use fetch return also includes that URL property so I can use a type Union here to say that our used fetch return will have a URL property but it's also going to have all of these other properties uh simple little refactor but now I have a common type that's going to have the state that we're actually using inside of our reducer so that looks good now we're going to be adding other State Properties later so I'm going to go ahead and create another type here just called the use fetch State and right now it's going to seem very contrived because I'm literally just going to say that the use fetch state is equal to the used fetch base state but that's just for now because we are going to be adding other State properties on here and properties on here that shouldn't be on here you'll see what I'm saying in a second but ultimately now that we have these types defined we can work on the reducer and so the reducer takes in the current state and state is of type use fetch State and then the reducer returns

Chapter 7 4:47

a simple reducer

that same state right and so the simplest reducer could literally just return the state that it received right and I mean this does nothing because basically it's going to take in a state that has a URL property and then just immediately return it but to make this actually useful we need to take in some information about how you want to change that state and that's where actions come into play and so I'm going to define a type here called my use fetch actions and the first type of action we have here is the ability to set the URL or update the URL and so your actions can be anything you can you can literally describe this type however you want and then we'll we'll pass it into the fun fun but a very common pattern you see is that an action will have a type if that is a string or some enum value and the type of action we want to perform on this state is to set the URL so when this action gets called we will in turn update the URL of our state now in order to update the URL we also need to know what the urall is is being set to and a common pattern here is to set a payload property so payload is just kind of like a generic term for some data that we need for this particular action um and

Chapter 8 5:08

defining action types

we could say that the payload is just a string right because our URL is a string but once thing that I like to do is have the payload be a partial part of our state and so in this case it's the full State again this will make more sense once we add new properties but in this case I would like my payload to have a URL property that is a string and you'll see why in a second it's going to make it easier to uh do these these nested updates we'll keep this here for now but I do want to refactor this so we have a little bit less duplication because right now we've got a URL string here and a URL string here bear with me okay so this is the type of action that can be performed on our particular State um and so the second argument to reducer is the specific action that is being performed and essentially what we can do is we can look at the type of the action and then use the payload to update the state and now this action is going to be of type use fetch actions and so the simplest way to take into account this action is to just have an if statement so we can say if action. type is equal to set URL then we want to update the URL and our function always returns the state and basically what we can do is we

Chapter 9 6:32

updating reducer state with actions

can say uh let's return an object let's take all the existing properties of state and then let's also take all of the existing properties of that specific payload right so whenever we combine the existing state which has a URL string with the payload which is going to have a URL string we now get a new object with the latest value now again this doesn't make a lot of sense when we only have one property but you can imagine we have a lot of different type of updator that need to run so the process of like setting that specific property is going to be very similar but essentially we always want to keep all of the previous state values and then only update the things that we are concerned about now there's a lot of other ways to write this I think at the end of the day we just want to return a copy of state that has the updates inside of it you could do this manually you could say URL is action. payload URL this also is completely valid right because this is setting the URL to be the latest thing uh but what I'll show you in a second it's going to make the code nice and reusable if we just spread the payload like this okay so this is our basic reducer and again it's a bit contrived right now but it'll start to make more sense as we add new properties into our state so the reducer takes in the

Chapter 10 7:46

review: what is a reducer?

existing state it takes in some action that is going to be performed on that state and then based on the action return returns a new state and so for this particular reducer if any other type were to be passed in here we don't have any code that manages it so we're always going to be returning the current state as it is we're not going to be modifying it but if the type is set URL then we'll set the URL so this is our reducer let's actually use it and what we'll do is we will comment out the use State here for URL and instead we're going to have the state and then this thing called dispatch which is going to let us update that state for our reducer and built into react is a hook called use reducer use reducer accepts a reducer so we can actually just pass in this reference here to use fetch reducer and then it also accepts the initial State because our reducer needs that initial state in order to return the initial State and in this case the initial state is just going to have a URL property and you can see here that before we were initializing it to initial URL so I'll do that here I'll say that this is the initial URL okay so

Chapter 11 8:13

use a reducer with useReducer

now we're using this reducer inside of our component the state that we get back is an object that has a URL property CU that's the latest value and then this this dispatch function is going to actually allow us to send off these actions because I don't want any of my code below to have to do anything different because below we're referencing URL directly um I could go through and say state. URL in every spot where I reference it but instead I'm actually just going to destructure it so I'm going to pull off the URL here and then the rest of my code is Happy the only spot that is not happy is this because update URL expected that we were going to return a function now this is another spot where we're going to need to update the types because before we said that this type would specifically be a set State action we're going to simplify things we're going to say that update URL actually just takes in a string URL and then does nothing with it so whatever string gets passed to this function we're going to use it to update State now for our purposes this will work just fine because the code that we wrote doesn't do anything special with our update URL and any any of our updater functions because technically a

Chapter 12 9:24

updating types and dispatching actions

set State action could accept a callback function but all of our existing code doesn't pass a callback function it just passes in the data so it's okay for us to make this type update if your code was doing something slightly different your typee here would need to be a like slightly more complicated but for our purposes update URL needs to take in a new URL return nothing and internally it just updates the URL so let's Implement that because now we don't have an update URL function but we can Define our own so we can say that we take in the URL which is a string and this is where we can actually use dispatch because this is where we want to call our reducer and update that internal URL inside the state that is returned from that reducer so here if we call dispatch you can see that it takes in an action and then we can pass in the type in this casee the type is going to be set URL and then our payload is going to be an object that has a URL property just like that and so essentially for every one of these State updaters we're going to pass in the type we're going to pass in the payload if this function gets called dispatch will in turn trigger a call to our reducer function it'll figure out okay what type was dispatched let's update the state

accordingly that new state will be returned and then we can use it everywhere else and so with this simple update here now all of our tests should stay passing the only thing we've changed is we've moved that URL State into this reducer instead of having a US state property directly but everything else is exactly the same so if I look at my tests my test should still be passing because the only thing I did was changed where that URL is being stored now if this is the only thing we had to do I would not refactor this to be a use reducer but like I said there are some other areas where it makes a whole lot more sense so let's let's continue refactoring now the next thing I'll do is I'm actually just going to refactor these other state values here because it's a very similar situation where we just have the state value to find and then we expose a function so the outside world can update it and so let's work on our request options so request options are of type request in it so this this is the thing that actually gets passed into the the fetch function and so this only exists on our state internally we don't expose this to the outside world you can see here that we don't return request options so request options needs

Chapter 13 11:13

when to use a reducer

Chapter 14 11:21

refactor options state into reducer

to exist on our use fetch state but not on our base state right because we're not returning it so this is where this type was actually useful is now this should have some request options uh which are optional but our of type request in nit and so now our state is a little bit more complex it has a URL and it has some request options and so the action for setting those request options is going to be very similar so I'll copy this um but it's going to have a different type and it's going to have a different payload so what I'm going to do here is I'm going to create a discriminated Union so our actions could be of type set URL but they could also be of type set request options and in the case of request options our payload could be request options which is of type request it but again this can be optional cuz it's possible to just set those to undefined and so now we have two different type of actions that can be fired off but now you can see where the repetitiveness might actually come in because we're going to do this one more time for our internal options so something that we could do instead is instead of manually defining this payload is we can actually say well

let's just pick that particular property off of our state here and then we don't have to manually Define it so in order to do that we can use the the pick helper which is built into typescript so instead of manually specifying an object with the URL property we could say okay let's pick from use fetch State the property URL and this now gives us a type that only has the URL property on it and you can see where this is just kind of like removes some some duplication because we don't have to manually specify the type we can just say hey use that that base state but then grab the specific property that we care about for this payload which is request options and so this cleans things up a little bit but now we need to take into account whenever an action is fired off with set request options and as you can see the way that we wrote this the action updator should be exactly the same because the payload could be one of two things it could be for the URL or it could be the request options but both of those just need to override that value inside of state so the simplest thing to do here is just add an or right we could say if or the action. type is equal to set request options and then we can see now the

payload could be one of two things it could be that we're updating the URL or it could be that we're updating the request options but in both scenarios we want to copy the previous state and then update that specific property and this should work just fine so now we can actually comment out this Ed State some things are going to break but instead we'll grab the request options and then their initial value is going to be the initial request options and then we need to destructure those request options off and then we also need to update our type so instead of using a a set State action here we'll just say this takes in the request options which could be undefined which is a request in it and then just returns nothing and so now we can update our type here so take in the request in it and then do something with it in this case we're just going to do a dispatch you guessed it are type is now set request options and our payload includes those request options simple as that and so at this point we can get rid of this use State and our test still pass so far there isn't any major benefit of moving this into a reducer uh except for the

Chapter 15 14:38

when to use a reducer

fact that we're kind of like consolidating these updates if anything we have more code now but the real benefit is going to come from all of our other internal State variables I kind of wanted to just get these refactors out of the way to get you used to the process of adding it to our state creating an action type and then using that action in side of our reducer so we have to do it one more time in this case with our options so let's get rid of the options here we now want our options to exist on state so here we have options and we have a custom type here it's called use fetch options so we'll we'll use that we'll update our function that sets it so this takes in the options which is type of use fetch options returns nothing so that looks good um we'll have a another action type of just set options and in this case we're just going to pick off the options property now here is where adding another or statement would also be very cumbersome and so this is why typically inside of reducers we use a switch case because it kind of cleans things up so let's actually convert this into using a switch statement instead so we can say

Chapter 16 14:59

continue refactoring options state

we're going to switch on the action. type like this and if we have the case where the action type is set options then we want to return our state like so but this is the exact same scenario for the case of set request options and it's the exact same scenario for the case of a set URL and so this is a little bit nicer than having a bunch of or statements essentially what this is saying is in the case of any one of these three types we basically just want to spread that payload into our state and also copy over the existing state okay so that looks good let's update our function to use it so this now needs the options where the initial value is going to be whatever was passed in or we set that default value like so then we'll destructure options here so it's available inside of our hook and then lastly We'll add our dispatching function here so update options receives the options which is of type uh use fetch options the type that we want to dispatch here is set options and then we want to pass those options into the payload and also this cannot be

undefined it must be defined okay so you you've gotten in the flow of basically add the state to our state type create your custom action type handle that specific action type inside of your reducer and then refactor the code to remove the use state so this is the basic process C of kind of like moving things out of use State now like I said if this is the only refactor we were making I probably wouldn't do this this code is like slightly more complicated there's actually even more code this is not the best use case for use reducer but what is is the fact that these three state variables are typically all updated together right whenever we fire off the fetch we set loading to true we clear the data set it to null and we clear the error and then whenever the fetch is done we set loading to false we set the data if there is any data we set error to null or if there was an error we set loading to false we set the data to null and then set the error to a specific error value so these three state values are kind of being always being updated together and so this is a very good use case for a reducer and because we're going to make that refactor I think it made sense to pull

Chapter 17 17:01

when to use useReducer

these other options into there as well and we kind of got used to how this specific reducer is going to work because it's going to get slightly more complicated now that we have a generic type here okay so first of all let's add these three state values to our state here and this is one of the reasons I made this base state is because you can see that the return value includes loading error and data but uh we want to include that in our fetch State as well so I'm actually going to move these three properties into our base state but now base State needs to be a generic type because we need to be able to specify what data is and then here I can actually just pass that generic type through and so our base state is now going to keep track of all four of these things and then our used fetch state gets a little bit more complicated because we need to take in that specific type and then pass that type to the base State and similarly all of our other uses of these needs that generic type so we're going to pass it through like so and in this case well where does t come from we're actually going to pass in that type whenever we create our reducer so we're actually going to pass the type

Chapter 18 17:53

moving fetch state into reducer

into to whenever we create that reducer because the type will come from whenever someone is actually calling our our custom hook but now we need some default values and so I'm actually just going to go ahead and comment out our use States here we're going to set our default value so loading sets up as false data initializes as null and error initializes as null and so now we've taken those initial values and we're specifying those on our state here but everywhere we were calling those Setters is broken um so we're going to have to update that and we will actually destructure from our reducer here so we're going to pull in data we're going to pull in error and we're going to pull in loading okay now we have to think about how do we group these specific actions I hinted at this earlier but basically there's a couple different scenarios right in the case of there not being a URL we basically just want to immediately stop trying to make this Fetch and then set set an error and so we could think of what do we call this so we could call this like uh fetch error or uh like set fetch error but if you think more generally we're also going to be doing a similar thing if there was ever like a throne error and

Chapter 19 19:15

finding and grouping actions

we're almost always setting data and error and then setting loading accordingly so in this specific scenario I think it makes sense to have an action that's called finish fetching or end Fetch and then it will set data it will set error and it will set loading accordingly so let's do just that let's create our custom action type here we will call it finish fetching and whenever we're finished fetching we need data and we need error because whenever finished fetching gets called loading should always be set to false and then we can handle this specific case in our switch here so in the case of finish fetching we want to spread the existing state in this case we'll spread the payload which is going to have error and data and then we'll always set loading to false and so you can see here how this is going to simplify some of our logic down below is where we don't always have to set loading false we can explicitly dispatch our action called finish fetching okay so if there was not a UR when someone fired off this hook we're going to dispatch an action the type is going to be finish fetching our payload is going to set data to null just like we were doing right here and then it's going to set our error to

Chapter 20 19:56

defining grouped actions

Chapter 21 20:27

replacing setState with dispatch actions

empty URL like so and then that allows us to get rid of this set State and also allows us to get rid of this set State and so now we have this nice named action that can actually update multiple properties and also handle some default cases that we don't need to explicitly specify every time like setting loading to false now let's use this same dispatch in a couple of other areas right so if there wasn't a URL when this Hook was fired off we're going to set the error the other place where we need to finish fetching is whenever we're setting the data so in the case of this we're going to set data equal to Json which is the data we got back from the API and then the error gets set to null so in this scenario we finish fetching clear out the error and set the data in this scenario we want to set the error to error. message so here we'll say finish fetching we're going to set data to null and then the error is going to be error. message and then we set it so that our specific hook will actually set loading to false and then we don't need to manually call set loading here now one other spot we could do this is right here under abort error is we could actually say okay well finish fetching

but set both data and error to null and that would be fine um but I think in a scenario where like there's no real arguments being passed in here or like always setting both of these to null I think that's a use case for its own custom dispatch right cuz we could simplify this much further if we just say abort touching we could make this so that we don't have to specify any payload and then we always set data in error to null if the abort fetching type was fired off so let's do just that so now we can have another action type called abort fetching and it doesn't need any payload because when that type gets called It's Always setting data to null Always setting error to null and then Always setting the loading to false and so we'll have one more case here in the case of abort fetching we'll spread our existing state we'll set data to null error to null and then set loading to false and so this cleans this up nicely right because we're not having to specify multiple things if if it's always going to do the same thing in that scenario so this is looking good I think the last spot we need is the case of setting loading to true and kind of like firing off our request and so this is the opposite of finishing in this

Chapter 22 21:41

when to define actions with no payload

Chapter 23 22:29

combining action types with no payload

case we need to start fetching or begin fetching so let's create one more action type for start fetching in the case of start fetching we always want to clear out the data clear out the error and uh set loading to true so we could actually reuse this type here where we we're not going to pass in any payload but the type is going to be slightly different in this case we'll call this a start fetching and we'll handle this almost exactly like abort fetching so we can add this case here where the case is start fetching but we set loading to true if the type is start fetching so we can say right here loading should be if the action type is equal to start fetching then loading should be set to true but if the action type is abort fetching then loading should be set to false so that should be all we need and so in this case we can actually get rid of both of these and then just make a dispatch to the type of start fetching and so now when our hook gets called if the URL is set it's going to start fetching it's going to then set data to

null set error to null and then uh set loading to true because we are starting the fetch now with that I think our refactor is done we can actually get rid of those State variables here the rest of our code should be exactly the same it's accessing all of our state variables we've got our finish fetching abort fetching finish fetching and then everything else looks good to me so if we did everything right all of our tests should still be passing and they are but now we've kind of grouped all of our state updates into some nice named action types now you might actually split this up into one other action because we have start fetching and then finish fetching and finish fetching is basically combining the idea of setting data and also setting the error you could split this off you could say fetch error or fetch success and in the case of fetch error we only specify the error property in the case of fetch success we only specify the data property that's completely up to you I like kind of like the idea of combining them together because it starts and then it finishes and so this is our refactor of taking all of those Ed States and combining it into a single reducer now in this

Chapter 24 23:43

review usage of reducer and dispatch

Chapter 25 24:04

other action type options

Chapter 26 24:31

tradeoffs to choosing useReducer

particular instance You could argue that we've increased the complexity right when you're looking at this code there's a lot more we have a lot of different action types uh we're dealing with typescript generics now this is definitely more intermediate react code so I think when a when a beginner comes across this code it's a lot to take in and so this is one consideration to make if you decide to write your code this way is the onboarding factor is potentially a little bit more especially if you have react developers that aren't used to this specific style but I would say the main benefit here is consolidating all of our state updates into a single spot right this in a sense is functional programming use fetch reducer is a pure function it takes in state it takes in action and then returns a new state and it's pure in that given the same state and the same set of actions it's always going to return the same type of state so it's a pure function and then the other thing is we've kind of Consolidated our logic right so before all of these these set states were kind of sprinkled throughout our hook and you can imagine doing the same refractor inside of a component you might have these set States all over the

Chapter 27 25:02

benefits of useReducer

place but now we've Consolidated them to a single location now we know that if there's ever any sort of bug or issue with the data not being the right thing we only have to look in one spot it's inside of our reducer right so like if for whatever reason we're getting some weird Behavior where maybe loading isn't getting set to the right thing that we needed to these are literally the only two places in this entire code example where we set the loading property and so this is where we can Target all of our debugging and I I think this is really one of the major benefits of refactoring into something like a use reducer is it consolidates all of your State updates into a single spot and basically the source of all bugs and the source of all things is potentially in this one location instead of being spread throughout your code all right thank you so much for watching there are a lot of other ways we could actually implement this and I'd love to see your solution so if you refactored this into a reducer and maybe you thought of some other ways to write it or other action types that we could use let me know down in the comments give a link to like a GitHub gist or a git repo and I'd be more than happy to take a look at it and if you

Chapter 28 26:15

thanks!

have any questions about this or if you have any uh complaints maybe you think that this wasn't a good refactor and you have some reasons why let me know down in the comments as well if you like this video drop a like and definitely subscribe if you want to see more all right I'll see you in the next one [Music]

[Music]

Quote it with credit and a link. Quoting Syntax