Intro to React Hooks- Part 5

Michael Rosenberg
3 min readApr 27, 2021

Before moving on to some of the other React Hooks, we’ll be going over one last example here with the State Hook. This post will go over how to use the useState Hook when the state variable is an array.

As always, before reading on, make sure to check out the previous parts of this series to get caught up.

Example

Let’s take a look at the code for this example, followed by a breakdown below:

// HookItems.jsimport React, {useState} from 'react';function HookItems() {
const [items, setItems] = useState([])
const addItem = () => {
setItems([ ...items, {
id: items.length,
value: Math.floor(Math.random() * 10) + 1
}])
}
return (
<div>
<button onClick={addItem}>Add Number</button>
<ul>
{items.map(item => (
<li key={item.id}>{item.value}</li>
))}
</ul>
</div>
)
}
export default HookItems// App.jsimport React from 'react';
import './App.css';
import HookItems from './components/HookItems';
function App() {
return (
<div className='App'>
<HookItems />
</div>
)
}
export default App

Here’s what’s happening above:

  1. In HookItem.js we have a functional component, HookItems.
  2. We import useState, and declare a state variable using the useState Hook and array destructuring, with the default value being an empty array.
  3. Next, we render the items in the JSX; we create ul tags, and then map through the items array to render an li for each item.
  4. Then, we add a button with an onClick set to a function addItem, that pushes new items into the array.
  5. We then define the addItem function; within this function, we call the setItems setter function; here, we need to pass in the value to set for the items being added to the array. If you recall from Part 4 of this series, the setter function does not merge and update automatically, or in the case of an array the setter function does not automatically append the item to the end of the list. So in order to handle this manually, once again we use the spread operator ( … ). So the argument to setItems will be an array, first using the spread operator to make a copy of the items array, and then pushing a new object into the array. For the object, we set id equal to items.length and we set value equal to a random number 1–10 (using the JavaScript Math built-in object methods).
  6. Finally, we import and render this HookItems component in App.js. If you then open your browser and click the button a few times, you’ll see random numbers showing up in a list format, for each item being added to our state variable.

Recap

Let’s review this example, specifically how we work with the useState Hook and an array as the state variable.

In our addItem function, we’re using the spread operator to make a copy of the items array. Then, we append a new item (in this case an object) to this array, and these two things are what’s being passed to the setItems setter function as an argument. Remember, the setter function is being used to update our state variable.

So each time we click our Button, the onClick calls our addItem function. And the function is making a copy of the items array, our state variable, while also appending a new item to the array. We then see each item in the array being rendered in the browser, using map to render each item as an li.

useState Summary

Before moving on to other React Hooks, let’s summarize what we’ve gone over with the useState Hook:

  1. The useState Hook let’s you add state to functional components; by calling useState inside a functional component, you’re creating a single piece of state
  2. In classes, the state is always an object and you can store properties on that object; with the useState Hook, the state doesn’t have to be an object, it can be an array, a number, a boolean, a string, etc.
  3. The useState Hook returns an array with two elements; the first element is the current value of the state, and the second element is a state setter function; you call the setter function with a new value to set the state, which will in turn cause the component to re-render
  4. In case your new state value depends on the previous state value, you can pass a function to the setter function; the setter function will receive the previous state as its argument
  5. When dealing with objects or arrays, always make sure to use the spread operator to make a copy of your state variable and then call the setter function to get the expected behavior

That concludes our examples for the State Hook, useState. See you next time in Part 6 when we go over a new React Hook, useEffect!

--

--

Michael Rosenberg

Software Engineer/Full Stack Web Developer | Ruby, JavaScript, React, Redux