Why React Hooks?

the first thing you should do whenever you're about to learn something new is ask yourself two questions why does this thing exist and what problems does this thing solve if you never develop a convincing answer for both of those questions you won't have a solid and a foundation to build upon when you dive into these specifics now these questions are specifically interesting in regards to react hooks react was the most popular and the most loved modern front-end framework in the JavaScript ecosystem when hooks were released and despite the existing praise the react team still sought necessary to build and release hooks lost in various medium blog posts and think pieces are the reasons one why and for to what benefit despite high praise and popularity the react team decided to spend valuable resources building and releasing hooks so to better understand the answers to both of these questions we first need to take a deeper look into how we've historically written react apps the first important date in Reax history is May 29 2013 this was when react was first released at Jay s conf and what's interesting about this version of react is a lot of the exact same principles that we know today still hold true back then when it was first released things like state props component composition really the only things that have changed are some of the api's so create class was the first way in which we created react components the reason react initially used the create class API was because at the time JavaScript didn't have a built-in class system of course this eventually changed and brings us to our next date January 17th 2015 this was when es6 was officially released and with that class declarations or a way to natively build classes in the JavaScript language now this put react in a tough position either continues using Cree class and fight against the progression of JavaScript or submit to the will of the Xmas crip standard and embrace classes as history has shown they chose the latter and as of January 27 2015 and react be zero point one three you could use native JavaScript classes to create your component according to the release toxic says we figured that we're not in the business of designing a class system we just want to use whatever is the idiomatic JavaScript way of creating classes so this was a big win as it aligned react more with the Ekman script standard and so then this was the way that we created our components all of our lifecycle methods were still the same but instead of using get initial state to add state to our components we could use the classes constructor method now though this was a clear step in the right direction reactive component wasn't without its trade-offs as I just mentioned with class components you initialize the state of the component inside of the constructor method as a state property on the instance however according to the ECMO script spec if you're extending a subclass in this case react a component you must first invoke super before you can use this specifically when using react you also have to remember to pass props to your super invocation next was Auto binding when you see create class react would auto magically bind all of the methods to the components instance for you with reactant component that wasn't the case very quickly react developers everywhere figured out that they didn't know how that this keyword work instead of having method invocations that just worked you had to remember to bind methods in the class's constructor if you didn't you would get this very popular cannot read property set state of undefined error now I know what you might be thinking first these issues are pretty superficial calling super props and remembering to bind your methods is annoying but there's nothing fundamentally wrong here second these aren't necessarily even issues with react as much as they are with the way JavaScript classes were designed both points are valid however even the most superficial issues become a nuisance when you're dealing with them 20-plus times a day luckily for us shortly after the switch from Greek class to react component the class fields proposal was introduced class fields allowed you to add instance properties directly as a property on a class without having to use constructor what that means for us is that with class fields both of our superficial issues we previously talked about would be solved we no longer need to use constructors to set the initial state of the component and we no longer need to bind inside of the constructor since we could use arrow functions for our methods so at this point we're good right well unfortunately not quite the move from curry class to react on component came with some trade-offs but as we saw class fields took care of those unfortunately there are still more profound but less talked about issues that existed with all of the previous versions that we've seen the whole idea of react is that you're able to manage the complexity of your application by breaking it down into separate components that you can then compose together this component model is what makes react so elegant it's what makes react react but the problem doesn't necessarily lie in the component model but in how the component model was implemented historically how we've structured our react components has been coupled to the components lifecycle this natural divide forces us to sprinkle relating a logic throughout the component you can see that in this example we have three separate methods component in Mal component that update and update rebo's to accomplish the same thing keeping rebo's in sync with whatever props that ideas to fix this we need a whole new paradigm for the way in which we handle side-effects and react components the next issue has to do with sharing non-visual logic when you think about composition and react odds are you think in terms of UI composition this is natural since it's what react is so good at but realistically there's more to building an app than just the UI layer it's not uncommon to need to compose and reuse non visual logic as well however because we react couples UI to a component this can be difficult historically or react hasn't even had a good answer for this so sticking with our example say we needed to create another component that also needed the repo state right now that state and the logic for handling it lives inside one component but we also need that inside of another component so the simplest approach to this would just be copy and pasting now that's tempting but not quite what we're going for this brings us to our next date February 11 2015 so Sebastian of the react team came up with this gist he said what if we had a function that function took in a component as its argument and then what it returned is another class component that class contain all of the logic that we wanted to share across multiple compile and then what it would return is the react element that was originally passed in as the component and all of us were kind of just like okay I guess that works so this introduced the topic of having higher-order components here we have a with rebo's higher-order component we stick all of the logic that we want to share across multiple components inside of the component that we return it takes in a component as its argument and then what it renders is the original element that was passed in passing it all of the original props as well as the state and then now whenever any component in our app needed a repos we could just wrap it in our with rebo's higher-order component now this works and historically along with another pattern called render props has been the recommended solution for sharing non visual logic however both of these patterns have some downsides first if you're not familiar with them and even when you are your brain can get a little wonky following the logic with our with repos higher or component we have a function that takes in the eventually rendered component as the first argument or returns a new class component which is where our logic lives it's a pretty convoluted process next what if we had more than one higher-order component we were consuming as you can imagine it gets kind of out of hand pretty quickly and even worse than this code is what eventually gets rendered higher-order components and render props force you to restructure and wrap your components this can eventually lead to what's called wrapper hell as we see here so here's where we're at with all of this we use classes for react components because that's what made the most sense at the time calling super props is annoying no one knows how that this key works okay at this point you probably know how the this keyword works but it's an unnecessary hurdle for some organizing our components by lifecycle methods forces us to sprinkle related logic throughout our components and react has no good primitive for sharing non visual logic so we need a new component API that solves all of these problems while remaining simple composable flexible and extendable this is what makes hooks so impressive is that react had all of these constraints they had all of these use cases they needed to solve and if somehow they were able to create an API that kind of encapsulated everything and the solution they came up with was just a function here's a quote from John Carmack sometimes the elegant implementation is just a function not a method not a class not a framework just a function so no more reactive component instead react shows to embrace functions so now just with that one move what happened was we solved most of these superficial issues that we saw earlier but now what we need is a way to add state to our components lifecycle methods and a way to share non-visual logic so this brings us to our very first hook called u state so this is the first of many hooks that you'll be seeing in this course what the rest of this video just serve kind of as a soft introduction we'll be diving much more deeper into hue state as well as other hooks in the future lessons so you stay as you see here takes in a single argument the initial value for the state what it returns is an array with the first item being the piece of state and the second item being a function to update that state typically it gets Rim is this where you use array D structuring to grab the first item being the state value and the second item being the way to update the state so now if we were to update our code it would look like this where in order to add our repo state and our loading state to our component we use the U state hook so this solves our problem of needing if you add state to function components next we need to figure out a way to add life cycles so here's something that may make you sad or happy depending when using react hooks I want you to take everything that you know about the traditional react life cycle methods as well as that way of thinking and forget about it we've already seen the problem of thinking in terms of the life cycle of a component the life cycle divided and actually forces us to sprinkle related logic throughout the component instead think in terms of synchronization think of anytime you've ever used a life cycle event whether it was to set the initial state of a component fetch data update the Dom anything the end goal was always synchronization typically synchronizing something outside of react lend an API request the Dom etc with something inside of react land component State or vice-versa when we think in terms of synchronization instead of lifecycle events it allows us to group together related pieces of logic to do this react gives us another hook called use effect use effect lets you perform side effects in function components it takes two arguments a function and an optional array the function defines which side effect to run and the optional array defines one to resync or rerun the effect in this code the function pass to use effect will run whenever username changes therefore syncing the documents title with whatever hello user name resolves to so now how can we use the use effect hook inside of our code to sync repos with our fetch repos API requests well it'll look something like this where any time ID changes the effect is going to rerun setting loading to true fetching the repos at that ID and then setting repos as well as loading based off of the response so now we've successfully gotten rid of reactive component constructor super this and more importantly we no longer have our effect logic sprinkled and duplicated throughout the component the last thing we need to figure out is sharing non visual logic so earlier I mentioned that the reason react didn't have a great answer to sharing non visual logic was because react couples UI to a component this led to over complicated patterns like higher-order components or render props as you can probably guess by now react hooks have an answer for this as well however it's probably not what you think there's no special built-in hook for sharing non visual logic instead you can create your own custom hooks that are decoupled from any UI so we can see this in action by creating our own custom use repos hook this hook takes in an idea of the repos that we want to fetch and to stick with a similar API will return an array with the first element being the loading state and the second element being the repo state so what's nice as any logic that's related to fetching our repos can be abstracted inside of this custom hook so now regardless of which component we're in and even though it's non visual logic whenever we need data regarding repos we can consume our use repos hook so at this point we've introduced state to our function components we haven't necessarily introduced life cycles but we've introduced a way to accomplish the same thing with the use of Beck took and we've seen how we can better share non visual logic and again what's so impressive about this is the new API is still simple it's still composable still flexible and it is still extendable the marketing pitch for hooks is that you're able to use state inside of function components in reality hooks are much more than that they're about improved code reuse composition and better defaults now there's a lot more about hooks that we still need to cover but now that you know why they exist you have a solid foundation that we can build on hello youtube if you enjoyed this video make sure you check out our full react ebooks course the link is in the description below what it will contain is a bunch of videos like this but also more importantly things like practice problems and quizzes and text sections to work through so you're not just passively learning instead you're going to get your hands dirty with react hooks

16 thoughts on “Why React Hooks?

  1. Just loved the way you introduced the design pattern of the hooks, and what problems it solves.
    I'm actually now very intrigued to go and read the hooks part in React's source code, to know how they implemented the reactivity there.

    Thanks. Keep going with what you do.

  2. I don't think you're making a compelling sales pitch for hooks in this video. The problems you list aren't really problems and even if they were –– nothing is being simplified in the example hooks you wrote. At the end of the day all you've done is use new semantics and shifted complexity elsewhere, not reduced the complexity.

  3. This is awesome. Thanks for sharing but I think you also missed talking about the beautiful combination of Context and the “useContext” hook. I think these together make using something like redux or mobx unnecessary in most cases. It’s extremely intuitive and less cluttered. Thanks for your content! Really liked how you explained the history of the “why”

  4. Actually I saw this at your instagram live .. but it wasnt clear.. Thanks alot for reposting this sir 🙂

  5. Teaching a workshop tomorrow, and this is such a powerful refresher on the history or how React components have been written over time. Awesome stuff Tyler!

  6. Supreme explanation, looking forward to this course greatly! Hopefully you'll use async/await/error boundaries when suitable 🙂

  7. Tyler, do you think we will eventually stop using class components and use hooks everywhere? And thank you for such a useful video on hooks

  8. Thanks for making some of the best informational videos about Javascript and sharing your knowledge with us!

Leave a Reply

Your email address will not be published. Required fields are marked *