'How to manage multiple states in React? [closed]

I have components in my React App, with more than 20 rows with:

useState()

Is that the correct way or to assign them in a object, is there some kind of differences ?



Solution 1:[1]

That is fine. Sometimes we can have 10-12 lines of useState() calls only. I usually combine similar states in one so that I can use a single variable in my component instead of 5.

Instead of:

const [a, setA] = useState('') 
const [b, setB] = useState('')
const [c, setC] = useState('')
const [d, setD] = useState('')
const [e, setE] = useState('')

I use:

const [letters, setLetters] = useState({
a: '',
b: '',
c: '',
d: '',
e: ''})

and update the state as:

setLetters(prev => ({...prev, c: 'hello'}))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Winter