Is it, and why is it a bad idea to mutate a state from React\'s new useState hook? I found no info on the topic.
Consider following code:
const [valu
You should never mutate state directly as it might not even cause a re-render if you update the state with the same object reference.
const { useState } = React;
function App() {
const [values, setValues] = useState({});
const doSomething = (name, value) => {
values[name] = value;
setValues(values);
};
return (
doSomething(Math.random(), Math.random())}>
{JSON.stringify(values)}
);
}
ReactDOM.render( , document.getElementById("root"));
You can give a function as first argument to setValues just like you are used to in the class component setState, and that function in turn will get the correct state as argument, and what is returned will be the new state.
const doSomething = (name, value) => {
setValues(values => ({ ...values, [name]: value }))
}
const { useState } = React;
function App() {
const [values, setValues] = useState({});
const doSomething = (name, value) => {
setValues(values => ({ ...values, [name]: value }));
};
return (
doSomething(Math.random(), Math.random())}>
{JSON.stringify(values)}
);
}
ReactDOM.render( , document.getElementById("root"));