Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Manipulating Arrays and Objects in State with React

In React, every component can handle its own state. This guide covers how to manipulate state with objects and arrays.

Nov 4, 2020 • 5 Minute Read

Introduction

At the heart of every app lies its state. No matter the kind of technology you use, your app relies on some sort of state, be it in-memory, on a physical disc, and so on. In React, every component can handle its own state, which might mean clicking a button or the content of a text input. These components are mostly referred to as smart components, whereas components which do not handle state are referred to as dumb components. In this guide, you'll learn how to manipulate state with objects and arrays. Sit tight!

State in Class Components

React components can be written as ES6 classes with state handled in the constructor function.

Consider the snippet below. <MyComponent/> has a state object in its constructor function, which is called before the component is rendered. Whenever the state object changes, React calls the render method on <MyComponent/>.

      import React from 'react'

class MyComponent extends React.Component {
	constructor(props){
		super(props);
		this.state = { date: new Date(), name: 'Kofi'};	
	}

	render(){
		return(
			<div>
						<p> Hello {this.state.name} , it is {this.state.toLocaleTimeString()
						<p>Date: {this.state.date.toLocaleDateString()}
			</div>
		)
	}
}
    

State in Functional Components (Hooks)

With the introduction of hooks in React 16.8, functional components can now also handle state in a simplified way. The snippet below is the class-based <MyComponent/> written as a functional component. The useState hook is a function that takes in a default value as a parameter (which can be empty) and returns an array containing the state and a function to update it. Array destructuring is used to extract the values from the result of the useState function call.

      import React, {useState} from 'react';

function MyComponent(){

	const [date, setDate] = useState(new Date())
	const [name, setName] = useState("Kofi");

	return(
			<div>
						<p> Hello {date.name} , it is {date.toLocaleTimeString()
						<p>Date: {date.toLocaleDateString()}
						<button onClick={setDate(new Date())}></button>
			</div>
	)
}
    

Manipulating Arrays

If you're integrating your React app with an API, you probably would like to store values obtained from the API call in an array in state without losing previous values the array contained. The spread operator helps you do that easily. Take a close look at the snippet below, which implements the spread operator in finalArray by "spreading" the contents of oldArray.

      const oldArray = ['peter piper', 'picked a pair']

const finalArray = [...oldArray, 'of pickle pepper']

console.log(finalArray)

// (3) ["peter piper", "picked a pair", "of pickle pepper"]
    

Using hooks, you can easily apply that to your state array, as shown below. The values can now be used to render a list of paragraph tags using the map function.

      import React, { useState, useEffect } from 'react';

const ProductsPage = () => {
  const [productsList, setProductsList] = useState([]);
  const [isLoading, setisLoading] = useState(true);

  useEffect(() => {
    fetch('http://127.0.0.1:8000/api/v1/products/all')
      .then((res) => res.json())
      .then((data) => setProductsList([...data]))
      .then(setisLoading(false));
  }, []);

	return (
    <>
      <Header />
      {isLoading ? (
        <div className='spinner-border text-primary' role='status'>
          {' '}
          <span className='sr-only'>Loading...</span>{' '}
        </div>
      ) : (
				productsList.map(product => {
							<p key={product.id}>{product.name}</p>
				})
      )}
    </>
  );
};

}
    

Manipulating Objects

Objects also support the spread operation, just like the code snippet above. Let's implement the same code with object spread.

      import React, { useState, useEffect } from 'react';

const ProductsPage = () => {
  const [productsList, setProductsList] = useState([]);
  const [isLoading, setisLoading] = useState(true);

  useEffect(() => {
    fetch('http://127.0.0.1:8000/api/v1/products/all')
      .then((res) => res.json())
      .then((data) => setProductsList({...data}))
      .then(setisLoading(false));
  }, []);

	return (
    <>
      <Header />
      {isLoading ? (
        <div className='spinner-border text-primary' role='status'>
          {' '}
          <span className='sr-only'>Loading...</span>{' '}
        </div>
      ) : (
				Object.keys(productList).map(product => {
							<p key={productList[product].id}>{productList[product].name}</p>
				})
      )}
    </>
  );
};

}
    

Conclusion

And that's it. You've successfully studied the art of state management with objects and arrays. Tackling state-related issues should now be a breeze for you. If you'd like to chat more about this topic, ping me on Twitter @DesmondNyamador.

Desmond Nyamador

Desmond N.

Desmond is a FullStack engineer, based in Ghana, West Africa. He enjoys teaching and upskilling software engineers and seeing the process of growth of individuals from beginner developers to masters in their fields.

More about this author