I would like to know if I can use setState hook multiple times in same function. For example, like this
import React, { useEffect, useState } from 'react';
function(props) {
const [color, setColor] = useState(0)
const [size, setSize]= useState(0)
const [weight, setWeight] = useState(0)
const onClickRandomButton = () => {
setColor(Math.random() * 10)
setSize(Math.random() * 10)
setWeight(Math.random() * 10)
}
return <div>
<button onClick = {onClickRandomButton}>random</button>
</div>
}
I have tested, but it doesn't work as expected. To set multiple values at once using hook, how should I do? Thanks
React calls your component for the first time. React finds a call to useState , creates a new Hook object (with the initial state), changes the current Hook variable to point to this object, adds the object to the Hooks list, and return the array with the initial state and the function to update it.
Explanation. As we learned earlier, we can use multiple State or Effect Hooks in a single component: function Form() { // 1. Use the name state variable const [name, setName] = useState('Mary'); // 2.
Yes, but you might not want to. With class components we would keep all of our state in one object. Then when we changed state with setState , we would provide an object and the API would "merge" its contents into the existing state for us. This doesn't happen with setting state in function components with useState .
You can use one useState with object value for updating the styles at once:
import React, { useEffect, useState } from 'react';
export default function (props) {
const [style, setStyle] = useState({ color: 0, size: 0, weight: 0 });
const onClickRandomButton = () => {
setStyle({
color: Math.random() * 10,
size: Math.random() * 10,
weight: Math.random() * 10,
});
};
return (
<div>
<button onClick={onClickRandomButton}>random</button>
</div>
);
}
And if in any method you want to update just one property, for example: color, you could do something like this:
...
const handleEditColor = color => {
setStyle({
...style,
color
});
};
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With