I have components in my React App, with more than 20 rows with:
JavaScript
x
2
1
useState()
2
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:
JavaScript
1
6
1
const [a, setA] = useState('')
2
const [b, setB] = useState('')
3
const [c, setC] = useState('')
4
const [d, setD] = useState('')
5
const [e, setE] = useState('')
6
I use:
JavaScript
1
7
1
const [letters, setLetters] = useState({
2
a: '',
3
b: '',
4
c: '',
5
d: '',
6
e: ''})
7
and update the state as:
JavaScript
1
2
1
setLetters(prev => ({prev, c: 'hello'}))
2