Hey there, I'm going to be honest. This is a post that I will make for myself for reference. I've just started learning React and I got a little confused.
So, what's the difference between () => {}
and () => ()
. I asked around and this was what I got.
() => {}
is this:
() => {
return something
}
() => ()
is the same but without the explicit return
statement:
() => (
something
)
It is mostly a one-line return statement. So it essentially comes down to a simplified version, which is:
() => return something
Or you can just do
() => something
There is also another form where you return a component.
() => <Component />
However, can you do this?
() => (
var i = 0
var a = i + 1
return a
)
This concludes to this:
() => (
return var i = 0var a = i + 1 return a
)
While that is wrong, you can do this.
() => (
return(
<div>
<p></p>
</div>
)
)
If you still feel slightly wonky about this, it is better to resolve to () => {}
this first.
Feel free to correct me if I'm wrong ya!
Top comments (7)
There is also the possibility to do:
void
will always result intoundefined
. This is useful as event handlers may change their behavior if a return value is given. Withvoid
this will not happen as you are guaranteed to returnundefined
.The only reason to use the above is to make one-liners. In the other hand you get one-liners with:
But that means you have to allow for such syntax and I think typically Prettier forces this to:
Personally I like this "spacious" style more rather than compacting everything into a mass of one-liners. And actually I'd rather write:
It is a bit shorter, and I like the old. Very much a stylistic choice and a matter of opinion.
I see. Thank you!
and
These are not the same.
This is a block of statements.
This is an expression
They are very different things.
An expression evaluates to a value.
A block executes statements and does not evaluate to a value.
One of the statements in the block may be a return statement which causes the call to the function to evaluate to the returned value.
Differentiating clearly between statements and expressions will make your life easier.
Unless you rewrite that return out or rewrite it to be in a block of statements, you cannot do this.
Thank you for this. I may need to have another glance at your examples for me to fully comprehend it!
Your last code is wrong, you can't use return inside
() => ()
return is only allowed in() => {}
.The difference is that
() => ()
return single expression and() => {}
is a block that require return.Great post!
Thank you!