React Hooks and State

Ronan McClorey
2 min readJan 24, 2021

--

Hooks are a feature that was added to React. Hooks allow us to use state and lifecycle methods inside functional components, which were previously only available in Class components. It benefits users as it makes code more reusable, cleaner to read, and eliminates the need for class components.

Photo by Tatiana Rodriguez on Unsplash

When working in React you can create one of two components functional or class. Before hooks, we needed to use class components when we needed to use state or add a lifecycle method.

State

Without hooks, if we wanted to use state in a component it would have to be a class component. We can initiate state by simply calling state setting it equal to an object with the key value pairs of the initiated state inside. We can update/change state with the setState() method. Then to use the state we can call this.state.name. Here is an example of what the class component would look like for a simple click counter:

The same component can be written out as a functional component using hooks. First, we have to import useState to be able to use it. Then we initialize state and set a reference to the state variable and a function to update/change state, as we as an initial value. Then to update state we call the function we named when initiating state. Similarly to reference state we use the the variable name we used while initiating state. To make this clearer below is the above code refactored with hooks.

As you can see even though this is a small example of code you can see that hooks can be useful in condensing the code and it is easy to read and follow.

Modern React with Redux [2020 Update] helped me understand and to be able to use hooks in React.

--

--

No responses yet