These functions seem to get used interchangeably in React tutorials but can't figure out the difference... or when to use which?
const SomeVal = () => {
...
}
const SomeVal = () => (
...
)
These functions seem to get used interchangeably in React tutorials but can't figure out the difference... or when to use which?
const SomeVal = () => {
...
}
const SomeVal = () => (
...
)
These are fundamentally different. The former arrow function syntax, () => {}
, allows you to have multiple statements inside the arrow function's body, i.e.:
() => {
console.log('Hello!');
return 'World!';
}
// When called, this logs Hello! and returns World!
But the latter, () => ()
, is an arrow function that implicitly returns an expression that is wrapped in parentheses (called the grouping operator). It does not explicitly allow for multiple statements:
() => (
'World' // only one expression that is implicitly returned
// Would work fine without parentheses (unless you want to return an object!)
)
// When called, this function returns 'World'
Of course, you could also create an unreadable arrow function that performs multiple operations using the comma operator:
() => (console.log('Hello!'), 'World!')
I assume you see this with React stateless components:
const Comp = () => (
<div>Hello World!</div>
);
This function (components are just functions) returns the <div>
element implicitly. But, using {}
, you can do some intermediary calculations instead of just returning right away:
const Comp = () => {
const msg = 'Hello World!';
return ( // Need to explicitly return here
<div>{msg}</div>
);
}
An arrow function with const fn = () => { ... }
creates a code block where you can have multiple lines of code. However for this case you need to have a return statement.
An arrow function with const fn = () => ( ... );
supports a single line of code and the return statement is implicit. The brackets around the function are optional so your function could look like
const sum = (a, b) => a + b;
const sum2 = (a, b) => (a + b);
const sumBlock = (a, b) => { return a + b; }
In essence, both do the same thing. But, the latter way of writing arrow functions allows your code to be slightly more concise if you only need a single statement.