Reputation: 13
I am a little bit confused with using useState() hook in React. I want to store some data in component state, for example values from form - name, minValue and maxValue. What my code should look like?
const [state, setState] = useState({
name: '',
minValue: 0,
maxValue: 9
});
or
const [name, setName] = useState('');
const [minValue, setMinValue] = useState(0);
const [maxValue, setMaxValue] = useState(9);
Is any of these approaches better or are they equal?
Upvotes: 0
Views: 363
Reputation: 1
The useState() returns your current state value and a method to update this state value. There you can set any kind of object, array or string etc. Like this:
const [someState, setSomeState] = useState('something')
To manipulate the state you have to call a function like so:
const someFunction = () => { setSomeState('new state') }
Hope that helpes.
Upvotes: 0
Reputation: 728
While both will work, I would consider the second one to be better, since it is easier to read and update. If you want to handle more complex objects, take a look at useReducer()
.
Upvotes: 3