How to use React hooks with useState

H
andrewgbliss
a year ago

In this article we are going to cover state management in React using the hook useState.

. . .

Getting Started

State management will enable us to dynamically store variables, arrays, and object in our application. By using React hooks we can change the state and have it update our application on the fly.

Let's start by creating an unordered list:

<ul>
  <li>Daniel</li>
  <li>Johnny</li>
  <li>Miyagi</li>
</ul>

How do we control this list, so that we can dynamically add names?',

We can use React state management.

useState

We need to bring in state before we can start using it.

import React, { useState } from 'react';

All of React hooks begin with the keyword "use". useState is how React uses state management. It is called a hook that let's us control state. Here is an example of how to set it up.

const [names, setNames] = useState();

The useState hook is a function, with the first argument being the default value of the state. It returns an array, with the first element being the state variable, and the second element is a function we can use to set state.

So when we click a button or trigger some event, we can add to the names state by calling setNames. This will trigger React to render our component again with the new state.

Example

import React, { useState } from 'react';

const App = () => {
  const [names, setNames] = useState([]);
  const [name, setName] = useState('');
  const handleChange = e => setName(e.target.value);
  const addName = () => {
    setNames([...names, name]); // Add the new name to the array
    setName(''); // Clear out the input field
  };
  return (
    <>
      <div>
        <input value={name} onChange={handleChange} />
        <button onClick={addName}>Add Name</button>
      </div>
      <ul>
        {names.map(name => (
          <li key={name}>{name}</li>
        ))}
      </ul>
    </>
  );
};

export default App;

This will create a state to hold a list of names, and a state to hole the name we want to add. When we type in the input field it will store the name in the state. When we click on the button it will add to the names array and render the unordered list with the new name.

Links

React Hooks

JavaScript Array Spread Operator

Next Lesson

In the next lesson we will get started using Material UI.


H
andrewgbliss
a year ago