Understanding useState's initial value

If you're coming over from React's class components, you might be confused about how useState works, particularly since you can now define what the initial value is.

Let's take a closer look.

You'd typically use it like this:

import React, { useState } from 'react';
const SomeComponent = () => {
const [someState, setSomeState] = useState('starting value');
return <div onClick={() => setSomeState('new value')}>{someState}</div>;
};

If you want to play with this example, check out the CodeSandbox.

In class-based components, you might be used to defining a whole bunch of initial state values inside the component's state object. That's no longer the case with useState. Instead, we tend to declare a single state value at a time, like so:

import React, { useState } from 'react';
const SomeComponent = () => {
const [someState, setSomeState] = useState('starting value');
const [someOtherState, setSomeOtherState] = useState(null);
const [importantState, setImportantState] = useState(42);
return <div onClick={() => setSomeState('new value')}>{someState}</div>;
};

The key difference is that the initial value of the state defined by useState can be anything you want it to be. It no longer has to be an object. A string, a number, an object, undefined, null - anything goes!

The other difference, is that calling useState returns you an array with two things in it: the value, and a function to set a new value. The typical approach to the array useState returns is to destructure it in the same line it's declared, as we saw above:

const [someState, setSomeState] = useState('starting value');

(Shameless plug for the useEffect book I wrote below)

Tired of infinite re-renders when using useEffect?

A few years ago when I worked at Atlassian, a useEffect bug I wrote took down part of Jira for roughly one hour.

Knowing thousands of customers can't work because of a bug you wrote is a terrible feeling. To save others from making the same mistakes, I wrote a single resource that answers all of your questions about useEffect, after teaching it here on my blog for the last couple of years. It's packed with examples to get you confident writing and refactoring your useEffect code.

In a single afternoon, you'll learn how to fetch data with useEffect, how to use the dependency array, even how to prevent infinite re-renders with useCallback.

Master useEffect, in a single afternoon.

useEffect By Example's book cover