React Hooks

Michael Abe
3 min readJul 22, 2021

React can be a fast and efficient way to build out an application. Manipulating the virtual DOM cuts down on the time that it takes to display a page, especially when making a change or real-time update. At the center of React is the idea of controlling the state of a component. State is an object in which you store property values of the component that is is in. When you change the state of a component, the component itself re-renders. An example of how one would set state and use it in class component could look something like:

Note that in the example above, the component that we are dealing with is a class component. To use state in the constructor like this you have to be using a class component. A functional component will not be able to do this. Any time that you want to change the state of this specific guitar you would have to change the state of it in this specific component, even if you were passing the state of it as a prop to another component further down the DOM tree.

If we wanted to change the color of our guitar to ‘Two Burst’ we would have to do something like the following.

The first highlighted area (lines 12–14) is the function that changes the state. we are using ‘this.setState’ to redefine what the value of the color key will be when we initiate the change of state. The second highlighted area (lines 27–29) are the button and click event that will call the ‘changeColor’ function to run. This is a fine and reasonable way to establish and alter the state of something in react, but since the addition of hooks, there is what I consider to be a better way to do state in React.

According to the official React documentation (Available here)

“Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. “

So the first major difference that we see straight away is that in order to implement hooks in our React app, instead of using class components like the example earlier, we will have to use a functional component instead. The way that we would write this using the “state” hook is the following:

Note that instead of a class component we are using a React functional component. By using deconstruction, we are able to set the states of the “brand”, “model”, “color”, and “year” all at once.

--

--