React Hooks Const Component vs Functional Component
Asked Answered
R

2

44

I understand the difference between a functional component and a class component, but what's the difference between const component to a functional component?

e.g

const Home = () => {
    return (
        <div>Home</div>
    )
}

To

function Home() {
     return (
        <div>Home</div>
    )
}

Both of them can use hooks, so what's the main difference?

Reprimand answered 18/4, 2020 at 17:10 Comment(0)
R
47

There is no effective difference. First is creating a function using Arrow function expressions syntax and storing it to a constant and the second is creating a plain function.

Both are functions that will perform the exact same task, return the component JSX code for rendering.

Also, there is no such term nor concept "Const Component"; there are "Functional Components" and "Class Components".

Rolanda answered 18/4, 2020 at 17:16 Comment(3)
I assume I didn't have the words to define it but my intention was for a declared function that returns JSX, thanks for correction. But is there any specific reason that I'll want to assign the arrow function into a constant or it doesn't really matter?Reprimand
There is a major difference between those two implementation, and that's the this, arguments and super scope and implementation, it's not just syntactic sugar. I suggest you read the mozilla wiki page that I include in my answer and also read this Q/A Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?. BUT in a case of defining a component there is actually no effective difference.Rolanda
Yes I know that, my question was referring to hooks because there is no use of 'this' and 'super'. I didn't understand the difference in hooks (with components, unlike handling events which I use a constant as a reference) because both of them can use hooks but I guess it doesn't really matter... thanks for your time :)Reprimand
C
0

One (the biggest?) practical difference is that JavaScript functions are hoisted but constants, for practical purposes, are not. Thus it is possible to use a function before it is declared:

const App = () => (
  <>
    <MyComponent />
  </>
)
function MyComponent() {}

But if you replace the MyComponent declaration with

const MyComponent = () => {}

The code will not work, until you move the component declaration up so the component is declared and initialized before it is used.

I liked this explanation. It's practical and to-the-point.

Christiansand answered 6/1 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.