Skip to content Skip to sidebar Skip to footer

Why Do I Need To Wrap SetState Callback In An Anonymous Arrow Function For It To Run After State Change?

I'm going out of my mind with this one. I have a react class that has some methods like this: handleSubmit = (e) => { this.setState({ isLoading: true, }, this.do

Solution 1:

What is confusing you is the order of evaluation in JavaScript, it's nothing React-specific.

If you have

foo(this.doSearch())

doSearch will be called immediately. That is, even before foo is called, and then the result of doSearch will be passed to foo.

You don't want that, you want to pass the computation to the setState function. That is, you want to pass the function doSearch, not the result of the function.

So what you actually want is

changePage = (e) => {
    this.setState({
        searchPage: e,
        isLoading: true
    }, this.doSearch);
}

Which means you're passing the function this.doSearch to setState. Of course, this.doSearch is equivalent to () => this.doSearch() (both are functions that, when called, call this.doSearch()).


Solution 2:

One calls it immediately and passes its return value as the callback to be used (bad). The other creates a function and that is used as the callback (good).

Its like accidentally writing an event listener like this:

// Assign console.log as the callbak
// Will print the event argument on click
// (just mentioning for completeness)
addEventlistener("click", console.log)

// vs

// Immediately print "a"
// Add undefined as callback
// (your first example [bad])
addEventlistener("click", console.log("a")):

// vs

// Add function that will print "a" after a click
// (your second example [good])
addEventlistener("click", () => console.log("a"))

Post a Comment for "Why Do I Need To Wrap SetState Callback In An Anonymous Arrow Function For It To Run After State Change?"