Introduction to the useState hook in React

useState is a hook that allows you to have state variables in functional components.

Previously, if you wanted to manage state in a component, you would have to use a class component.

Now we know what it is - on to the hooks!

The syntax basically looks like this:

    const [counter1, setCounter1] = useState(0);

So whats going on here?

The useState functionality gives us access to 2 values. The first values stores whatever we want to save in state, and the second is a method that let's us set that value. You can name these values whatever you want, as long as they are in the same order.  

We can set an initial state to our value by passing a value to the useState call. In this case, I've given it a value of 0

That's our state set up! But how do we use it?

We can reference these like any other variable in JS. For example:


    <div>Counter 1: {counter1}</div>

or in another function:

    function doubleCounterValues(){
      setCounter1(counter1 * 2)

That's it! Since you can have as many of these hooks as you like, the useState hooks makes it super easy to isolate, access, and edit state values for different elements of your app.

Check out this code sandbox:

This is part of the React bite-size series of posts. Check out the rest here!