loading...
Cover image for React functional components: const vs. function

React functional components: const vs. function

ugglr profile image Carl-W Updated on ・2 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 (as 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 then me, or know more differences please let me know!

Posted on Jun 3 by:

ugglr profile

Carl-W

@ugglr

React / React Native Software Engineer, former Senior Robotics Hardware Engineer.

Discussion

markdown guide