Everything You Need To Know About "useState"

Everything You Need To Know About "useState"

React Hooks: Part - 2

In the previous article we discussed about the fundamentals of React hooks. In this blog, we are going to talk about the useState hook in detail so you can start building stateful functional components.

One of the most important parts of any application is managing state. So understanding how to manage state is incredibly important. Before hooks were introduced the only way to modify state was with class components and this.state, but React has introduced hooks, specifically the useState hook, which is a new way to handle state inside of functional components.

From Classes To Functions

In order to understand how the useState hook works, we first need to look at how the state is managed in-class components. For this article, we are going to use a simple counter component for all examples.

Essentially all this component does is create a counter with a plus, minus, and reset button and by default, the counter has a value of 0 when it first renders.

Now let’s look at how we can convert this class component to a function component with useState. To start with we will use the following base code.

Creating initial state

In the class component example, the initial state is defined in a constructor as an object which contains all the state for the component.

constructor(props) {
  super(props)
  this.state = { count: 0 }. //Initial State
}

Obviously, function components do not have constructors, so instead the useState hook takes the initial state as an argument.

Why we pass an argument in the useState function?

It’s the initial value of the current value of the variable. If we code like this,

useState(initialState)

Why there are two variables as state & setState?

Normally when we call useState function ,it returns pair of values. Therefore we declare 2 variables for store current value(state) and updated value(setState).

const [state, setState] = useState(initialState)

If we were to map the class component directly to useState we would end up with something like this.

const [state, setState] = useState({ count: 0 })

Then we can compare the difference between the function base react hook component and the class base react component. Before we use the useState hook, we should import useState dependency like this.

import React, { useState } from 'react';

function Example() {
       [count, setCount] = useState(0);
}

Let’s add the code for updating our state into our function component.

Conclusion

In this article, we looked deep into the React state hook. We saw many facets of the React state hook. It might not be comprehensive at first, but with time you will get the hang of it.

Let me know your thoughts in the comments!! Let's talk more about React hooks in the next blog. See you there!

Happy coding :)

Thank you!