React functional components: const vs. function

React functional components: const vs. function

Β·

3 min read

I have been performance optimizing our app recently and as such, I have been getting into the nitty gritty of Javascript. One of the things I thought about is if there's any real difference between declaring a component like this:

const MyComponent = () => {
    return(
      ..
    )
}

vs.

function MyComponent() {
    return(
      ..
    )
}

In this form, the function syntax is slightly shorter.

And then?

At times, we can write the arrow function like this:

const MyComponent = () => (...)

If we put normal parenthesis after the arrow we don't need to write the return. So it's shorter if we can return immediately.

And then?

Another thing I have seen people talk about is the export of the component.

export default function MyComponent() {}

vs.

const MyComponent = () => {}

export default MyComponent

The function syntax gives us the ability to export default the component in place.

And then? (any Dude where's my car fans here?)

Hoisting

Turns out the biggest reason (what I could find) is due to hoisting. Let's look at an example with Valid syntax:

// I like to write my components before I use them

const MyComponent = () => {}

const AlsoMyComponent = () => {}

const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)

And then? Let's look at invalid syntax:

const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
// I like to keep my components at the bottom

const MyComponent = () => {}

const AlsoMyComponent = () => {}

This example πŸ‘† will engage your linter to throw an error. Because the components are used before they are declared.

So if you like to keep your components on the bottom, and use them before they are declared we can write them with the function syntax, and have them hoisted to the top of the file.

 const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
// I like to keep my components at the bottom

function MyComponent() {}

function AlsoMyComponent() {}

This example πŸ‘† will not engage your linter, because when we run the file it will look like this to the JavaScript engine:

// Components are hoisted to the top.

function MyComponent() {}

function AlsoMyComponent() {}

 const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
// I like to keep my components at the bottom

πŸ‘€ where did they go?

And then?

That's it! I think...? If you have a different idea than me or know more differences please let me know!

Thanks for reading

Like and subscribe for more content like this πŸš€

Looking for a remote developer job? Checkout my side project remoet.dev for a great compilation of resources.

Did you find this article valuable?

Support Carl-W by becoming a sponsor. Any amount is appreciated!

Β