setState has a form that accepts a callback updater. This updater is invoked when this state transition actually occurs (since setState may be asynchronous), accepting state and props of the component as explicit arguments at the time of state setting. Is there any difference to referring to these arguments vs. this.state and this.props? The docs say:
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.
My motivation to know is that I have some pure functions of props and state in this component to calculate some derived values that are sometimes fed back into state. I'd like to avoid rewriting these functions when they're needed in setState.
One big difference is that
this.statewill only update after all currently queuedsetStatecalls have finished:If the
this.stateupdated immediately, you'd see the count jump from 0 to 2 to 4, etc, but it doesn't; it updates one-by-one, becausethis.statedoesn't update immediately.In contrast, using the callback form's argument does provide you with the possibly-just-updated value.