I really like the new React hooks and I\'m using them frequently for a project I\'m working on. I\'m coming across a situation where I want to use the prevState in the
For objects you can use the spread operator to use prevState
within your setState
call.
const [stateObject, setObjectState] = useState({
firstKey: '',
secondKey: '',
});
setObjectState((prevState) => ({
...prevState,
secondKey: 'value',
}));
// stateObject = {
// 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 (
Updates Second key to 'not empty'
First key: {object.firstKey}
Second key: {object.secondKey}
Third key: {object.thirdKey}
);
};
// Render it
ReactDOM.render(
,
document.getElementById("react")
);