Using previous State with spread operator in React

760 Views Asked by At

I am learning React and I have a question. Sometimes we use the previous State when we want to set a new value:

import React, { useState } from "react";

function HookCounter() {
  const initialCount = 0;
  const [count, setCount] = useState(initialCount);
  return (
    <div>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount((prevState) => prevState + 1)}>
        Increment
      </button>
      <button onClick={() => setCount((prevState) => prevState - 1)}>
        Decrement
      </button>
    </div>
  );
}

export default HookCounter;

This is because we are building the new state on top of the previous state.

Does that mean that if we use the spread operator (for example in an array or an object), we don't need to use the previous State? Because spread gives us the previous State already?

For example

import React, { useState } from "react";

function ArrayCounter() {
  const [items, setItems] = useState([]);

  const addItem = () => {
    setItems([
      ...items,
      {
        id: items.length,
        value: Math.floor(Math.random() * 10) + 1,
      },
    ]);
  };
  return (
    <div>
      <button onClick={addItem}>Add a number</button>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.value}</li>
        ))}
      </ul>
    </div>
  );
}

export default ArrayCounter;

Thank you!

1

There are 1 best solutions below

2
Luis Lara On

In an object literal, the spread (...) syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

With the spread operator you're creating a copy by value of the object items.

Does that mean that if we use the spread operator (for example in an array or an object), we don't need to use the previous State? Because spread gives us the previous State already?

Yes, if the state have not been updated by any previous calls.

For more information of the spread operator please read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax