Curriculum
Course: React
Login

Curriculum

React

Text lesson

useState

The React useState Hook enables us to manage state within a functional component.

State typically refers to data or properties that need to be monitored and updated within an application.

Import useState

To utilize the useState Hook, we must first import it into our component.

Example:

import { useState } from “react”;

Note that we are destructuring useState from React, as it is a named export.

For more information on destructuring, take a look at the ES6 section.

Initialize useState

We initialize state in our functional component by calling useState, which takes an initial state and returns the current state along with a function to update it.

  1. The current state.
  2. A function that updates the state.

Example:

Set up the state at the beginning of the function component.

import { useState } from "react";

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

Again, note that we are destructuring the values returned by useState.

The first value, color, represents the current state, while the second value, setColor, is the function used to update the state.

These names are variables that can be customized to whatever you prefer.

Finally, we set the initial state to an empty string with useState(“”).