DEV Community

Lokesh
Lokesh

Posted on

useState in React

What Is useState?

useState is a React Hook that allows us to add and manage state in a functional component.

In simple words, useState helps us store a value and update it when needed.

For example, we can use state to store:

  • A counter value
  • User input
  • A selected product
  • A login status
  • Data from an API

How to Import useState

First, we need to import it from React.

import { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

Basic Syntax

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

Here:

  • state → stores the current value.
  • setState → updates the value.
  • initialValue → the starting value.

Simple Counter Example

import { useState } from "react";

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

    function increment() {
        setCount(count + 1);
    }

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={increment}>Increase</button>
        </div>
    );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

When the button is clicked:

  1. The increment() function runs.
  2. setCount(count + 1) updates the state.
  3. React re-renders the component.
  4. The updated value appears on the screen.

Another Example: Updating Text

import { useState } from "react";

function App() {
    const [name, setName] = useState("");

    return (
        <div>
            <input
                type="text"
                onChange={(event) => setName(event.target.value)}
            />

            <h2>Hello, {name}</h2>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

As the user types in the input field, the name state is updated and displayed on the screen.

Why Do We Use useState?

useState helps us create interactive React applications.

It can be used for:

  • Counters
  • Forms
  • Dropdown menus
  • Show/hide content
  • Shopping carts
  • Product selections

Top comments (0)