DEV Community

Cover image for React Hooks: useState
mikkel250
mikkel250

Posted on

React Hooks: useState

Normal react code would use a class component and use this.setState to manage the state.

Hooks is a way to write functional components but use state inside of them like you would a class component.

First, import the hook you want to use from React.

useState gives us back two parameters inside of an array. Use array destructuring to declare, in this order, state value, and the function that will modify that state value. You can name these two items whatever you want (you’re just declaring variables here), so make the names explicit. E.g., if you wanted to set the name to the logged in user, a simple example would be like the below, where the name is being modified by the function setName, and useEffect is setting it to ‘Mikkel’ (as the inital state).

import React, {useState} from 'react';

import Card from '../card/card.component';

const UseStateExample = () => {
  const [name, setName] = useState('Mikkel');

  return (
  <Card>
      <h1> { name } </h1> 
      <button onclick={() => setName('Andrei')}>Set Name to Andrei</button>
   </Card>
      );
};

You would use a new useState hook for each property you want to set or change, much like this.setState is called for each property that is being set or changed.

Top comments (0)