DEV Community

Cover image for The React useState Hook
Nathan B Hankes for Vets Who Code

Posted on

The React useState Hook

The React useState hook (function) allows users to update the state of a function component. Historically, only class components had state capabilities, and these only applied to objects. However, the function component useState hook can be used with booleans, objects, arrays, strings, numbers, etc.

When we build React components with state, we allow components to render dynamically based on user input. To get started, we import useState and create a function component:

import React, { useState } from 'react';

export default function Demo() {
  return (
    <div>

    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

The useState hook is called directly inside the function component, like so:

import React, { useState } from 'react';

export default function Demo() {

const [user, setUser] = useState('');

  return (
    <div>

    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Let's break down how this hook is constructed. It's declared as a const variable and has two values, a state component and the name of a function you will call to change the state. Additionally, the setState function is passed the initial value as its argument.

1.) A state variable: user
-The state variable preserves value in between function calls, so this is what you will call to display the current state of user.

2.) A function that updates state: setUser
-This creates the name of a function that you will call to change the state. React has already built in the functionality, so your only requirement here is giving this function a name and calling it where you need it.

3.) The initial state: ('')
-This value us what your component will render until the state is updated.

Now let's take a look at how these values are used inside of the function component:

import React, { useState } from 'react';

export default function Demo() {

const [user, setUser] = useState('');

  return (
    <div>
      <p>
        Welcome {user}
      </p>

      <form>
        <label>
          Name:
        </label>
        <input type="text"
          value={user}
          onChange={event => setUser(event.target.value)}
        />
      </form>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

When the user types their name into the form input element, the setUser function is called because it is invoked by the onChange function. This updates the user state variable and will then display this updated state where it is called in the paragraph element.

Top comments (1)

Collapse
 
jacobmgevans profile image
Jacob Evans

Take the "red pill" useState under the hood is essentially useReducer, if I have even two useStates, I start looking at how I can convert them to a useReducer. That's assuming I am not using XState already lol