DEV Community

Rachel Williams
Rachel Williams

Posted on

The State Hook

This is part two of my series on React Hooks. To check out part one where I talk about the useEffect hook, here is the link.

A Quick Refresher

In this blog I will talk about the useState Hook. As a refresher, React hooks are meant to be used in function components. For example here is a function component from my Concert Buddy application:

const Logo = () => {
  return (
    <div className="logo">
      <img src={logo} alt="Group of people"></img>
    </div>
  )
}

Hooks do not work in class components, which were previously used if you needed to use state within your component. Here is where the hook useState comes in.

The State Hook

This hook allows you to use state within a function component, so you no longer need to use a class. If I wanted to introduce state to my Logo component shown above, I could do so with useState. Here is an example of how I would do that:

import React, { useState } from 'react';

const Logo = () => {
  const [imgClicks, setImgClicks] = useState(0);

  return (
    <div className="logo">
      <img src={logo} alt="Group of people" onClick={() => setImgClicks(imgClicks + 1)}></img>
    </div>
  )
}

Above I declared my state within the first line inside the component. imgClicks is the name of my state variable and setImgClicks is similar to the setState function from class components.

useState is passed the initial value that you want your state to have, which in this case is 0. With hooks, state doesn't have to be an object. In this case, state is an integer. When a user clicks on the image in my div, the setImgClicks function will be called to set the new state. This state is now accessed by just using the variable imgClicks, since function components don't have a this keyword. In class components, a piece of state would be accessed within this.state. For example, if Logo was a class component and its state looked like this:

{
 imgClicks: 0
}

This piece of state would be accessed as this.state.imgClicks.

How Does This Work?

The useState hook returns a pair, the current state and a function that updates it (in our case that function is setImgClicks). That is why the variables are declared within an array. This syntax is called array destructuring and allows you to declare multiple variables at once. Here is the documentation on that.

Since useState returns a pair, the first variable in your array will be set to the first of the returned pair(the current state) and the second variable will be set to the second (the function that updates state). Because of this, you can name these variables within the array whatever you would like.

On the first render, the state will be initialized with the value passed to useState. When setImgClick is called, the component will re-render and the new state value will be passed to the component. The current state can be shown in your component by using the variable you declared it with. For example, if I wanted to display the amount of clicks on the image I would include:

<p>The image has been clicked {imgClicks} times</p>

Multiple State Variables

If you want your component to have multiple state variables, you will call useState for each variable. Here is an example from the docs:

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

Once again, the state can be a variety of data types, not just an object. The docs also mention that when using hooks, state is updated by replacing the entire value, instead of merging it (like with this.setState()). Due to the fact that state is replaced, the docs recommend to, "split state into multiple state variables based on which values tend to change together." This will avoid having to manually merge your state if you are using an object. The previous link has a great example of this.

Conclusion

The state hook is a really nice way to include state in your component. I think I like it better than using a class component, since it is more straightforward than dealing with an object with multiple state variables in it. Have you used the state hook in any of your projects? I would love to know!

spongebob

Top comments (0)