Reputation: 5187
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
Upvotes: 29
Views: 29601
Reputation: 792
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
});
};
// or
const handleEditColor = color => {
setStyle(prevState => ({
...prevState,
color,
}));
};
...
Upvotes: 28
Reputation: 23763
I believe unstable_batchUpdates
will works for hooks as well as it works for class-based components. Besides prefix unstable_
it's mentioned by Dan Abramov and in React-Redux docs so I consider it's safe to use it:
import { unstable_batchUpdates } from 'react-dom';
...
const onClickRandomButton = () => unstable_batchUpdates(() => {
setColor(Math.random() * 10)
setSize(Math.random() * 10)
setWeight(Math.random() * 10)
})
Upvotes: 6