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 (
<div onClick={() => doSomething(Math.random(), Math.random())}>
{JSON.stringify(values)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
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 (
<div onClick={() => doSomething(Math.random(), Math.random())}>
{JSON.stringify(values)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>