'How to handle 15+ useStates in reactJS
ReactJS question: Essentially I have 20 components that require useState to handle their state to know whether it is okay to show these components. Each component is based off of A separate value. I was wondering if it is bad practice or if there is a better way of doing many useState declarations. Instead of having 20 lines of useState. Thanks. Let me know if you have any questions
Solution 1:[1]
You can store state in an object like this:
const [state, setState] = useState({
name: 'John',
age: 27,
height: 182
})
When you need to update your state you just need to use spreading, this would guarantee you only change the value/s you intended to change while the rest stays the same:
setState({
...state,
age: 28
})
You can also still make references to your previous state if you need to:
setState({
...state,
age: state.age + 1
})
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 | Avi Cohen Nehemia |
