how to update multiple state at once using react hook react.js
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
});
};
...
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)
})