DEV Community

Cover image for React Hooks: useState

React Hooks: useState

I've been tinkering with computers since I was a teen. I'm currently pivoting from my current role as Tech Support manager to Full Stack Web Developer. I'm actively seeking employment in the field.
・1 min read

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 (
      <h1> { name } </h1> 
      <button onclick={() => setName('Andrei')}>Set Name to Andrei</button>

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.

Discussion (0)