I know I should not mutate state directly in React, but how about situation when I use function:
onSocialClick = e => {
const id = e.target.value;
this.setState((prevState, props) => {
prevState[id] = !(prevState[id]);
return prevState;
});
};
Is it a mistake to modify passed object?
EDIT:
It turns out that most of us were wrong here. React docs state it clearly now:
state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props
Thanks to @Tomáš Hübelbauer for pointing it out in the comment.
setState() does not immediately mutate this. state but creates a pending state transition. Accessing this. state after calling this method can potentially return the existing value.
React compares the previous state with the updated state to decide if the component needs to be re-rendered. Modifying the state directly will disturb this process. As a result the component will behave unexpectedly.
yes, but, honestly, it's subtle. There are two problems with mutating the state. First, setState() is actually asynchronous: meaning, React doesn't handle your state change immediately.
A cleaner way would be to refer directly to the property you want do edit:
doIt = () => this.setState(({ [id]: prevValue }) => ({
[id]: !prevValue,
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With