const [description, setDescription] = React.useState({
"key1":"first value",
"key2":"second value",
"key3":"third value"
}
)
I have an object like the one provided above. i tried deleting a key from the object with the function below.
const remove = (key) => {
delete description[key]
}
the problem i am having is, when i call this function the key is deleted form the object, but react does not update the state.
CodePudding user response:
the problem i am having is, when i call this function the key is deleted form the object, but react does not update the state.
That is because you should not mutate state. Using delete description[key]
will mutate the state, and doesn't inform React that a re-render should be triggered.
You should use setDescription
to inform React about a state change. And instead of mutating the existing state, create a new one without the key
property. This can easily be done with destructuring assignment.
const remove = (key) => {
setDescription(({ [key]: value, ...description }) => description);
};
In the solution above we extract the value of the key
property and store it in the value
variable. All other properties (without key
) are collected in a new object and stored in the description
variable.
This process essentially creates a copy of the old description without the key
property and uses it as the new state.
If you pass remove
as a property to other components you could consider using useCallback
as well. This stabilises the identity of the remove
function and could result in less re-renders.
const remove = useCallback((key) => {
setDescription(({ [key]: value, ...description }) => description);
}, []);
Normally you pass your dependencies in the dependency array at the end, but because the identity of setDescription
is stable you can omit this dependency.
If all the dependencies have a stable identity or the dependency array is empty, the resulting function has a stable identity as well.
CodePudding user response:
Note that you're mutating a local instance of your state. You should update the state through the useState
hook.
const remove = (key) => {
setDescription(description => ({
...description,
[key]: undefined
}))
}
Note that you should never mutate your state! This can cause bugs in your application. So in the code above, we make a new object, copy the data we have, and then just set [key]
to undefined, effectively deleting the value there.