I know that I should not mutate state directly in React, but what about the situation when I use the function:
onSocialClick = e => {
const id = e.target.value;
this.setState((prevState, props) => {
prevState[id] = !(prevState[id]);
return prevState;
});
};
Is it wrong to modify the passed object?
EDIT:
It turns out that most of us are wrong here. React docs now clearly state :
prevState is a reference to a previous state. It should not be directly mutated. Instead, changes should be presented by creating a new object based on input from prevState and props.
Thanks @ Tomáš Hübelbauer for pointing this out in the comment.
source
share