Skip to content
Advertisement

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 ?

Advertisement

Answer

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'}))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement