Max RozenMax Rozen
TwitterArticlesNewsletterUses

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

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 153 React developers who signed up this month!

    rssTwitterGitHub

    © 2020 Max Rozen. All rights reserved.