React useState Hook

The useState Hook in React enables state management within function components. State usually represents data or properties that an application needs to track.

Tutorials dojo strip

Importing useState

To incorporate the useState Hook, you must import it into your component.

Example

At the beginning of your component, import the useState Hook:

JavaScript

Notice that we use destructuring to import useState from React as it is a named export.

Initializing State with useState

To initiate state, invoke useState within your function component.

useState takes an initial state value and returns a pair of values:

  1. The current state.
  2. A function to update the state.

Example

Set up state initialization at the top of the function component:

JavaScript

Once again, we destructure the values returned by useState.

  • The first value, fruit, is the current state.
  • The second value, setFruit, is the function to update the state.

These variable names can be customized to your liking.

Finally, we initialize the state with an empty string: useState("").

Reading State

We can now use our state anywhere in our component.

Example

Utilize the state variable within the rendered component:

JavaScript

Updating State

To update the state, employ the state updater function.

Directly modifying the state, e.g., fruit = "banana", is not allowed.

Example

Use a button to change the state:

JavaScript

What Can State Hold?

The useState Hook can manage strings, numbers, booleans, arrays, objects, and combinations of these.

You can create multiple state Hooks for individual values.

Example

Create multiple state Hooks:

JavaScript

Alternatively, you can use one state Hook to hold an object.

Example

Use a single Hook to maintain an object:

JavaScript

Since we’re now tracking a single object, reference the object and its properties when rendering the component (e.g., vehicle.make).

Updating Objects and Arrays in State

When state is updated, the entire state is overwritten. What if we only want to modify the color of our vehicle?

Calling setVehicle({color: "green"}) would remove the make, model, and year from our state. We can use the JavaScript spread operator to help us.

Example

Utilize the spread operator to update only the color:

JavaScript

Tutorials dojo strip