React Hooks — What Are They?
Recently I have been working on a solo project and chose to reopen the book to working with React.js. And since I have learned React as a student there have been some updates to the usage, and manipulation of how we handle state. Hooks. Previously we would have to use “this.setState()” in a callback function. And then write in what we wanted the state to be, or how we wanted to update state. Now we have the magic of Hooks.
What Are Hooks?
Hooks are functions that let you “hook into” React State and LifeCycle features from functional components. Just as a warning Hooks will NOT work inside class components. They let you use React without classes. Thus abstracting a lot of code that we were used to writing out with our class components. You can also utilize hooks to reuse stateful behavior between two different components.
Why Do We Use Hooks?
In short from the description of what we know from WHAT they are, we can assume that Hooks are a faster way of handling state in a callback function as opposed to writing out constructor functions, and even the tedious class components. Personally I am a little biased to the class component. I lean on the side of building more explicitly so you know how your code is functioning step by step. But even I can see the benefits of using hooks. Right off the bat, I can already tell there is going to be dryer code. Less code is not necessarily always the best, but in this case it could save a lot of time.
Where Do We Use Hooks?
Seeing as we can only use Hooks in a Functional Component, where would we use a hook? Our component always has to render with JSX and have a explicit return line. Our Hooks are going to live in the top level of our component right before our return line. This is so that every time our component renders on the React DOM, our hook gets compiled as apart of our component, thus when you click on a button, or type something in. We have a hook to handle that functionality for us.
How Do We Start Using Hooks?
Hopefully this has been an informative intro into the world of Hooks. I want to be able to inform you, as well as, learn with you. Next week we will dive into using hooks, the syntax and what the difference is between updating state in a class component, and using a Hook in a functional component.