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

139
Vistas
Is there a way to dynamically choose which state I want to update in react?

For example if I have a bunch of useState hooks such as:

const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [location, setLocation] = useState('')

and a function that takes a string value such as:

const handleClick = string => console.log(string)  // Name

Is there any way of dynamically choosing which state I update by passing the string value to the function call? Something along the lines of:

const handleClick = (string) => {
    console.log(string)  // Name
    set${string}('John Doe')
}
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

You can achieve this behaviour by grouping your states into one

const [state, setState] = useState({
  name: '',
  age: 0,
  location: '',
});

const handleClick = (key, value) => {
  setState((prev) => ({...prev, key: value}))    
}
about 4 years ago · Santiago Gelvez Denunciar

0

A single object is usually used for this.

const [state, setState] = useState({
  name: '',
  age: 0,
  location: ''
})

const handleClick = (key, value) => setState({...state, [key]: value});

You could also do something like this:

const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [location, setLocation] = useState('')

const map = {
  name: setName,
  age: setAge,
  location: setLocation
}

const handleClick = (string) => {
    map[string]('John Doe')
}
about 4 years ago · Santiago Gelvez 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