useState

Learn how to add and manage states in function components.

Initializing the state

This Hook returns a value as well as a function to us, which we can use to update the value. We can initialize the state using this Hook in the following way:

const [state, setState] = useState(initialState);

During the first rendering of a component that uses this Hook, this value is equal to the initialState that you pass to the state. If the parameter that has been passed in is a function, it will use the return value of the function as its initial value.

Updating the state

When the update function is called, React ensures that the function always has the same identity and does not create a new function whenever the Hook is called. This is important because it reduces the number of renders and also means that we do not need to pass any other dependencies (as is the case in useEffect() or useCallback()).

The useState() Hook will return an array to us of which the first value always denotes the state and the second value is always a function that we use to update the said value. Due to array destructuring, we aren’t limited in naming this value and function. However, conventions have developed that follow the pattern of value / setValue (for example, user and setUser). Of course, you could also go for something like changeUser and updateUserState.

Updater function

The mechanism of actually updating the state is very similar to that of this.setState(), which we already encountered in this lesson. The function can either receive a new value that replaces the current old value, or we can pass an updater function to the function. The updater function receives the previous value and uses the return value from the function as its new state.

Let’s suppose we have an array of values. We will use the updater function to append a new value to the array like this:

const [myArray, setMyArray] = useState(initialArray);
setMyArray(oldArray => [...oldArray, newValue]);

Updating the state of objects

In contrast to this.setState(), objects are not merged with their previous state. Rather, the old state is completely replaced by the new state. To illustrate this, let’s have a look at the following example:

Get hands-on with 1200+ tech skills courses.