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

185
Visualizações
Using prevState Callback function in UseState react Hook

I have some array of products inside filteredProducts variable and wanted to sort them according to the price and newly added products. When using prevState like this without having { } in the callback function, the code runs fine.

useEffect(() => {
    if(sort === "newest") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        );
    }
    else if (sort === "asc") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a ,b) => a.price - b.price)
        );
    }
    else {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => b.price - a.price)
        );
    }
}, [sort]);

But when using { } for the prevState callback function like this

if(sort === "newest") {
        setFilteredProducts((prevState) => {
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        });
    }

, it is just throwing error in console.

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

0

When using the brackets you are declaring a function body, and need to return a value, i.e. the next state. Arrow functions without a function body use an implicit (vs explicit) return.

setFilteredProducts((prevState) => {
  return [...prevState].sort((a, b) => a.createdAt - b.createdAt);
});
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