DEV Community

Cover image for How to use useState()
Michael Mathias
Michael Mathias

Posted on

How to use useState()

React's useState hook is an essential tool for managing state within functional components. This hook lets you add a state variable to your component to allow stateful behavior and update components in response to events or user interactions.

Usage of useState

To start using useState, import it from the 'react' package at the top level of your component.

import { useState } from 'react';

Next, declare a state variable with array destructuring. The naming convention for state variables is [something, setSomething].

const [age, setAge] = useState(24);

useState returns an array with two items:

  1. The current state, initially set to the initial state you provided. 24 in the example above.
  2. The set function that lets you change the current state to another value in response to a user interaction or other event.

Call the set function with some next state to change the current state.

setAge(21);

Updating State Based on Previous State

To update state based on the previous state, pass an updater function instead of the next state. The set function only affects what useState will return starting from the next render; it does not change the state in the already running code.

function handleAgeClick() {
  setAge(age + 1); // setAge(24 + 1)
  setAge(age + 1); // setAge(24 + 1)
  setAge(age + 1); // setAge(24 + 1)
}
Enter fullscreen mode Exit fullscreen mode

Each setAge(age + 1) call becomes setAge(24 + 1). Fix this by using an updater function.

function handleAgeClick() {
  setAge(a => a + 1); // setAge(24 => 25)
  setAge(a => a + 1); // setAge(25 => 26)
  setAge(a => a + 1); // setAge(26 => 27)
}
Enter fullscreen mode Exit fullscreen mode

The updater function takes the pending state and calculates the next state from it. I named the pending state argument 'a' which is the first letter of the state variable 'age'. This is a common naming convention you can follow.

Avoid Recreating the Initial State

function CustomerOrders() {
  const [orders, setOrders] = useState(createInitialOrders());
}
Enter fullscreen mode Exit fullscreen mode

If you invoke a function as your initial state, the result will only be used for the initial render but the function will be called on every render. This can be wasteful but can be solved by passing the function as an initializer function to useState instead.

function CustomerOrders() {
  const [orders, setOrders] = useState(createInitialOrders);
}
Enter fullscreen mode Exit fullscreen mode

React only calls your initializer function during initialization and not on every render.

Objects and Arrays in State

You should not mutate your existing objects since, in React, state is read-only.

form.lastName = 'Smith';

Rather than mutate your objects, replace the whole object and create a new one with the spread operator.

setForm({
  ...form,
  lastName: 'Smith'
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

By understanding and effectively utilizing useState, you can enhance the functionality and interactivity of your React components, making your applications more dynamic and responsive. To learn more about useState and everything React, please take a look at the React reference pages.

Top comments (0)