Max RozenMax Rozen

What's the deal with 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.

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');

Do you struggle to keep up with best practices in React?

I send a single email weekly with an article like this one to help improve the quality of your React apps. Lots of developers like them, and I'd love to hear what you think as well. You can always unsubscribe.

    Join 43 React developers who signed up last week!


    © 2020 Max Rozen. All rights reserved.