0

What is the difference between:

this.setState(produce((draft) => { draft.name ='name'}

and

this.setState(produce(this.state, (draft) => { draft.name ='name'}

can someone explain me this?

Mykyta
  • 230
  • 2
  • 5
  • 16

1 Answers1

1

In most cases both would act the same

  1. produce((draft) => { draft.name ='name'}) returns a function that wraps argument with a Proxy and applies the mutation. setState allows developer to pass a function that will be called with current state.

  2. produce(this.state, (draft) => { draft.name ='name'}) returns the result of applying mutation to a Proxy of the first argument. setState allows to pass "updated state" thus it will also work.

The first approach is preferable because of the following

  1. If called rapidly in sequence you usually want next state to be built on top of the mutated previous state (famous counter example). And mutation function version of setState is the way to go.
  2. It is less characters to type.
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98