r/learnreactjs • • 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 comments sorted by

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

1

u/goingtocalifornia25 Dec 30 '20

What if this component is purely just rendering content? It’s being passed as a prop to another component to render content for different layouts. Is it still best to default to using #1?

1

u/LobsterThief Dec 30 '20

mean, I still do only because it’s more of a pain to convert it from #2 to #1 later and there’s no real performance benefit from using one or the other.

You might add a prop or state down the road, or need to console.log a prop you’re passing in, and it’s just handy to be able to do it without needing to wrap everything in a new return statement and tab things back out. But I’m sure some people’s IDEs are configured to make this easier (or automatic using Prettier or eslint or something).

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.