Reputation:
I'm reading Learning Redux by Daniel Bugl (which by the way is outstanding) and in the "FilterList component" section code example there is an action creator invocation that looks like this:
onClick={() => setFilter(category)}
and one like this:
onClick={clearFilter}
So it looks like when there are no arguments invocation works with just function name and when there are arguments then a more verbose syntax, in this case the arrow function syntax needs to be used. I'd like to verify this with the community here.
If I can do clearFilter
just like that then why can't I do setFilter(category)
without the arrow function syntax?
Upvotes: 1
Views: 73
Reputation: 9096
myFunction
is a reference to a specific function, which can be passed around, assigned to a variable, etc. myFunction(...)
is a call to a function. If you try to pass that, you'll be passing whatever that function call returned.
You can't do setFilter(category)
because you'd be passing the result of that function call, not the function itself. That's why you wrap the call in an anonymous arrow function (() => {...}
, where the curly braces are optional for simple functions), and pass that in.
While not specific to ES6 or React, you'd probably find it useful to learn more about JavaScript functions over at MDN web docs.
Upvotes: 1
Reputation: 67489
Because it's the difference between passing a reference to a function and calling a function. Remember that JSX gets transformed into a call to React.createElement()
, and props get turned into an object. Here's how it looks:
// before
<SomeComponent
onClick1={clearFilter}
onClick2={() => setFilter(category)}
onClick3={setFilter(category)}
/>
// after
React.createElement(SomeComponent, {
onClick1 : clearFilter,
onClick2 : () => setFilter(category),
onClick3 : setFilter(category)
});
For onClick1
, we're passing a reference to a named function. For onClick2
, we're passing a reference to an anonymous function that calls another function when it runs. But, for onClick3
, we're calling setFilter(category)
as we render, and then using the result of that as the value for onClick3
. That's not what you want.
Also, note that this actually has nothing to do with Redux and action creators. It's actually just about React, JSX, and how functions work in Javascript.
Upvotes: 0