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

155
Visualizações
Is there an easier way to reset states in React?

My React app has a form to add a new product and each product has a number of properties. When the product is added I redirect the user to the saved products page, and they can edit any saved products. I've run into some (not major) issues with the states. In some areas when editing, the state displays another products attributes because it has not been updated.

I want to clear the state so that if a product attribute's state isn't updated it is simply an empty string. Right now I'm doing this:

const resetStates = () => {
    setName("");
    setDescription("");
    setPrice(null);
}   

These are only some of the states being used, so it's cumbersome to have to reset all of them like this. Is there an easier way?

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

0

You can aggregate the state properties into a single object, like class components' state.

[formContent, setFormContent] = useState({name:'',desc:'',price: null});


const resetStates = ()=> {
    setFormContent({name: '', desc: '', price: null});
}

However the react docs seem to slightly prefer the separate state variables over a single object, since unlike this.setState updating a state variable using hooks, replaces its value.

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