DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Raphael Chaula
Raphael Chaula

Posted on

How to update object or array state in React

Ever tried to update object or array state directly in React?
I did that, the state of my component didn't change.
Destructuring the object/array was the solution.

When you update the state, create a new array/object by destructuring the one in the state, manipulate it then set it as a new value in the state.

Object

import React, { useState } from 'react';

const States = () => {

  const [objectValue, setObjectValue] = useState({});

  const updateObjectValue = (key, value) => {
    // Destructure current state object
    const objectvalue = {
      ...objectValue,
      [key]: value,
    };
    setObjectValue(objectvalue);
  };

  return <Component/>;

};

export default States;
Enter fullscreen mode Exit fullscreen mode

Array

import React, { useState } from 'react';

const States = () => {

  const [arrayValue, setArrayValue] = useState([]);

  const updateArrayValue = (value) => {
    // Destructure current state array
    const arrayvalue = [ ...arrayValue ];
    arrayvalue.push(value);
    setArrayValue(arrayvalue);
  };

  return <Component/>;

};

export default States;
Enter fullscreen mode Exit fullscreen mode

Happy Hacking!

Top comments (6)

Collapse
 
matjones profile image
Mat Jones

Or even better, use immutable data structures, for example Record and List from Immutable.js, or Drafts from Immer.js.

Collapse
 
raphaelchaula profile image
Raphael Chaula Author

Yes

Collapse
 
click2install profile image
click2install • Edited on

Or use array methods like concat so you're not increasing your time complexity using iterator semantics.

Your Array example is not updating state as you intended due to poor nomenclature. If you have to spread you can just setState(value => [ ...value, someNewValue ]);, which IMO is better served by setState(value => value.concat(someNewValue)); where the latter is using array semantics not iterator semantics.

Collapse
 
raphaelchaula profile image
Raphael Chaula Author • Edited on

Good point.
But my point is when you want to update array state, don't act on the array state directly, you need to create another array from the state array and there are multiple solutions for that, I chose destructuring. that's all.

Collapse
 
ahmedwebdevloper profile image
AhmedWebDevloper

Raphael , Thanks for this sol

Collapse
 
raphaelchaula profile image
Raphael Chaula Author

You are welcome

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await