DEV Community

Sebastian Duta
Sebastian Duta

Posted on

Complete Guide to useState Hook in React

In this article, we are going to look at how you can leverage the useState hooks in React apps, as it's one of the most basic concepts you need to be familiar with.

The useState hook is also available in React Native, so in general, pretty much all the concepts can be translated into the mobile world.

What are Hooks in React?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

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.

What is useState in React?

The useState hook allows you to add state to React function components. It returns a stateful value, and a function to update it.

The useState hook is a way to add state to function components in React. It accepts a single argument, which is the initial state, and returns an array with two values: the current state, and a function that updates it.

Creating the React App

To get started, you will need to create a React app. If you already have a React app, you can skip this step.

First, install the create-react-app package:

npm install -g create-react-app
Enter fullscreen mode Exit fullscreen mode

Then, create a new React app:

create-react-app my-app
Enter fullscreen mode Exit fullscreen mode

Basic useState Code Example

Now that we have a React app set up, let’s look at a basic example of how to use the useState hook.

In this example, we’ll create a component that displays a count. It will have a button that will increment the count when clicked.

First, let’s create a new component called Counter:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

This code creates a component called Counter that renders a <p> element with the current count, and a button that increments the count when clicked.

The useState hook is used to add state to the component. It accepts a single argument, which is the initial state, and returns an array with two values: the current state, and a function that updates it.

In this example, we use the array destructuring syntax to assign the current state to the count variable, and the function that updates the state to the setCount variable.

The count variable holds the current state, which is initialized to 0. The setCount function is used to update the state. It accepts a single argument, which is the new value for the state. In this example, we pass in count + 1 to increment the count by 1.

Advanced Use Cases of useState

The useState hook can be used to store more complex state in React components. For example, you can use it to store an array or an object.

Let’s look at an example of how to use the useState hook to store an array. In this example, we’ll create a component that renders a list of items. It will have a button that will add a new item to the list when clicked.

First, let’s create a new component called List:

import React, { useState } from 'react';

const List = () => {
  const [items, setItems] = useState([]);

  return (
    <div>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <button onClick={() => setItems([...items, 'new item'])}>
        Add item
      </button>
    </div>
  );
};

export default List;
Enter fullscreen mode Exit fullscreen mode

This code creates a component called List that renders a list of items. It uses the useState hook to store an array in the items variable. The setItems function is used to update the state.

In this example, we use the spread operator to add a new item to the array. The spread operator creates a new array with the existing items, plus the new item.

Caveats of useState

The useState hook has a few caveats that you should be aware of.

First, the state is only updated when the setState function is called. If you call setState with the same value, the state will not be updated.

Second, the state is not automatically updated when the props or context change. You will need to use the useEffect hook to update the state in response to changes in props or context.

Finally, the state is not automatically passed down to child components. You will need to use the useContext hook to pass the state down to child components.

Conclusion

In this tutorial, we looked at how to use the useState hook in React. We covered the basics of the useState hook, as well as some advanced use cases. We also looked at some of the caveats of the useState hook.

Using the useState hook is a great way to add state to React function components. It’s simple to use and allows you to add state without writing a class.

Top comments (0)