Tutorials Videos Menu
Website Pro NEW

React useState Hook


State holds data that changes over time — counters, form fields and toggle menus depend on it.

State generally refers to data or properties that need to be tracking in an application.


Why this matters on Global Tuts

Understanding state updates and re-renders is the core of interactive React UIs.

Common beginner mistakes

  • Mutating state objects/arrays in place
  • Expecting immediate state after setState
  • Storing derived data in state unnecessarily

Written by Mohammad Ashraf for Global Tuts learners.

Import useState

To use the useState Hook, we first need to import it into our component.

Example:

At the top of your component, import the useState Hook.

import { useState } from "react";

Notice that we are destructuring useState from react as it is a named export.

To learn more about destructuring, check out the ES6 section.


Initialize useState

We initialize our state by calling useState in our function component.

useState accepts an initial state and returns two values:

  • The current state.
  • A function that updates the state.

Example:

Initialize state at the top of the function component.

import { useState } from "react";

function FavoriteColor() {
  const [color, setColor] = useState("");
}

Notice that again, we are destructuring the returned values from useState.

The first value, color, is our current state.

The second value, setColor, is the function that is used to update our state.

These names are variables that can be named anything you would like.

Lastly, we set the initial state to an empty string: useState("")