Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
When to update state based on previous state in useState hook in React/Typescript

I have seen quiet a few examples on how to update state based on previous state, but I don't see much explanation on when to update state based on previous state, most examples use a counter example, but what if I was setting a object in state, would this still be based on the previous value or can I just update the state. e.g

const exampleData = [
    {
       text: 'Example name',
       value: 1
    },
    {
       text: 'Example name 2',
       value: 2
    }
]

  const [asset, setAsset] = useState(exampleData[0]);

  const handleClick = (event) => {
      setAsset(event.target.value) 
  }

So in the example I am updating the state in the handleClick function, but would I need to update it based on the previous value or not?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you want to access previous state, avaiable in setState action

const [state, setState] = useState(false);

const handleClick = () => {
    setState(prev => !prev); // true
    setState(prev => !prev); // false
}

Notice: setState is async action

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda