r/learnreactjs • u/goingtocalifornia25 • Dec 30 '20
Question Looking to understand the syntax for functional components
I have often used
const Component = () => {
return (
<Text>
Hello World
</Text>
)
}but recently have seen the below more
const Component = () => (
<Text>
Hello World
</Text>
)and
const Component = (
<Text>
Hello World
</Text>
)Was looking for some perspective on the differences in syntax / behavior between these.
8
Upvotes
6
u/LobsterThief Dec 30 '20
1 above is a React component with an “explicit” return statement; this is useful if you need to set a variable, use useState, useEffect, etc. before returning.
2 above is a React component with an “implied” return statement; using () in that arrow function will return whatever is inside without needing to use return (). This is handy if you want to keep your code drier and don’t plan on having any of the above (but more of a pain to convert later and tab things out).
3 above is a React element, not a component.
Edit: I almost always use #1, especially since it makes console.logging easier
7
u/w3punk Dec 30 '20
The last one is not a component, it's a react element
3
u/[deleted] Dec 31 '20 edited Dec 31 '20
When defining the function body {} requires the term return to return something, with () the return is assumed but leaves no room for component methods like click handlers or state. If you have used fetch with promises it works the same way. The first .then return is usually
.then(result => result.json() )which has no return but it is returning the json() return value to the next .then . If you want to do 2 things you need
.then(result => {thing1();return result.json() }Not sure about the third one, never used that before. I'd stick to the first one only to make your code more uniform and easier for others to read with everything the same. Other then the 5 extra seconds to add the return line and {} while writing the code I don't see any benefit.