ReactJS - prevState in the new useState React hook?
state updater
from useState
provides a callback pattern which returns you the previous state which you can use to update the current state
const [ someState, setSomeState ] = useState( new Map() )
setSomeState(prevState => prevState.set( key, value ) )
In order to use Maps, you'll need to clone it before manipulating the values. Otherwise, it's mutating the original Map
and React doesn't handle mutatable state
.
const handleChange = useCallback(({ target: { name, checked } }) => {
setCheckbox(prevState => {
return new Map(prevState).set(name, checked);
});
}, []);
Updated Working Example:
For objects you can use the spread operator to use prevState
within your setState
call.
const [object, setObject] = useState({
firstKey: '',
secondKey: '',
});
setObject((prevState) => ({
...prevState,
secondKey: 'value',
}));
// object = {
// firstKey: '',
// secondKey: 'value',
// }
The snippet below show an example of using prevState
for setting the state of an object.
const {useState} = React;
const Example = ({title}) => {
const initialState = {
firstKey: 'empty',
secondKey: 'empty',
thirdKey: 'not empty',
}
const [object, setObject] = useState(initialState);
const withPrevState = () => {
setObject((prevState) => ({
...prevState,
secondKey: 'not empty',
}));
}
return (
<div>
<h5>Updates Second key to 'not empty'</h5>
<p>First key: {object.firstKey}</p>
<p>Second key: {object.secondKey}</p>
<p>Third key: {object.thirdKey}</p>
<button onClick={withPrevState}>
Update with prevState
</button>
<button onClick={() => {setObject({secondKey: 'not empty'})}}>
Update without prevState
</button>
<button onClick={() => {setObject(initialState)}}>
Reset
</button>
</div>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>