I am using React's setState
method, and calling another function when the state has been updated.
Is there a preferred approach as to how to call the function that is passed to setState
as a callback.
Both of the approaches below work but is there any performance implications of using one over the other?
this.setState(prevState => {
return {
result: '1-0'
}
}, this.clearResult(500))
or
this.setState(prevState => {
return {
result: '1-1',
}
}, () => this.clearResult(500))
My clearPin
method looks like the following. All of this code is within a React component.
clearResult(time) {
setTimeout(() => {
this.setState({
result: '0-0'
})
}, time)
}
There's a correctness implication: The first one is incorrect, the second one is correct. :-)
In your first example, you're calling
this.clearResult(500)
and then callingsetState
(with the result of callingthis.clearResult(500)
—undefined
, in your example — as its second argument).this.setState(prevState => { ... }, this.clearResult(500));
is just likefoo(bar())
— first it callsbar
, then it passes the result of calling it intofoo
.In your second example, you're passing a function into
setState
that it will call when the state is updated.You want the second form (or one of the various equivalents to it).
Here's proof that your first example is calling
clearResult
before callingsetState
, and before your state change callback is called:whereas with
() => this.clearResult(500)
instead,clearResult
is called aftersetState
(and after the state change):Side note 1: If you want, you can be a bit more concise:
Side note 2: There's no need to use the function form if the new state you're passing isn't based on current state or props. In your example, it isn't, so yours is one of the places where using the non-callback form is okay:
That would not be okay if you were using something from
this.state
orthis.props
. In that situation, use the callback form and itsprevState
andprops
parameters. Always. And there's little harm in always using the callback form, the overhead of a function call is exceptionally trivial on modern JavaScript engines. (It was even trivial on the slowest JS engine of this century: The one in IE6.)More on that here and here.