Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Understanding React's setState method

I understand the below code adds a new object to an array of objects but fuzzy on a specific syntax: setProductList([array, obj])

From what I'm seeing, the setProductList function takes in an object. That object consists of an array and an object. So how does it add the object to the array? is this built into JS or React?

// array of products
const Products = [
  {
    item: "basketball",
    price: 3,
    description: "basketball desc",
  },
  {
    item: "football",
    price: 5,
    description: "football desc",
  },
];

// setting state
const [productList, setProductList] = useState(Products);

// handling click
const handleClick = () => {
   // Don't quite understand the syntax of below block
   setProductList([
      ...productList, // spread creates a copy of the array
      {
        item: "baseball",
        price: 4,
        description: "baseball desc",
      },
    ]);
  };

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

What you are seeing is Spread operator (...)

Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.

By writing [ (element inside) ], you did create a new array. ...productList alone does not create a new array

You could understand ...productList as it helps you write shorter code, instead of writing like this

setProductList([
  productList[0],
  productList[1],
  // ...
  productList[productList.length - 1],
  {
    item: "baseball",
    price: 4,
    description: "baseball desc",
  },
])

Another example that could help you understand the spread operator, is the use of Math.max. Basically, syntax of Math.max is Math.max(value0, value1, ... , valueN).

For example you have an array of N elements, because Math.max solely could not take an array as arguments, so to calculate max of the array, you could iterate each element and compare

const arr = [1, 3, 2]
let max = -Infinity

for (const num of arr) {
  max = Math.max(max, num)
}

console.log(max)

But now with spread operator, you could achieve the same result in a shorter way

const arr = [1, 3, 2]
let max = Math.max(...arr)

console.log(max)

about 4 years ago · Juan Pablo Isaza Relatório

0

This feature is built into js and called Object Spreading

Example

var x = [1, 2] // an array

console.log(x)

// spreads an array, and put an extra element
var y = [...x, 6]

console.log(y)

so, the state hook returns a function here - setProductList That just updates the state to the new array.

it's a common practise. See this detailed answer for in deth explanation

about 4 years ago · Juan Pablo Isaza Relatório

0

Ok, the code which you don't understand basically is setting a new copy of the current array, BUT including the new element (it'd be like push a new element in the array. BUT push would modify the original array. In this case, it's making a copy and pushing the value to that new array)

Lets go line by line. We have:

 setProductList([
      ...productList,
      {
        item: "baseball",
        price: 4,
        description: "baseball desc",
      },
    ]);

We will define:

 setProductList([                       // Line 0
      ...productList,                   // Line 1
      {                                 // Line 2
        item: "baseball",               // Part of Line 2
        price: 4,                       // Part of Line 2
        description: "baseball desc",   // Part of Line 2
      },                                // Part of Line 2
    ]);                                 // Part of Line 1(]) & 0())
  • With Line 0 (setProductList) we are setting a new value to productsList because react hooks and useState. (https://reactjs.org/docs/hooks-state.html)
  • With Line 1 we are creating a new copy of the array ([...oldArray]) will return a copy of the previous array (You can read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
  • With Line 2, we are including a new value at the end of the new array.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda