Search code examples
javascriptreactjsuse-statecode-injectionsetstate

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')
}

Solution

  • 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')
    }