Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mutate state passed to setState function?

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.

like image 452
Tomasz Mularczyk Avatar asked Apr 09 '17 10:04

Tomasz Mularczyk


People also ask

Does setState mutate state?

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.

Why is mutating state not recommended in React?

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.

Can we mutate state in React?

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.


1 Answers

A cleaner way would be to refer directly to the property you want do edit:

doIt = () => this.setState(({ [id]: prevValue }) => ({
  [id]: !prevValue,
}));
like image 86
Fez Vrasta Avatar answered Oct 28 '22 05:10

Fez Vrasta