728x90
728x90

const Component vs. function Component

들어가며

  • 리액트(React.js)에서 @const Component@ 형태의 화살표 함수 방식 @function Component@ 형태의 함수 선언 방식으로 컴포넌트를 선언할 수 있다.
  • 위의 두 가지 방법에 대한 차이점을 정리해본다.

 

① 화살표 함수 방식

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

 

  • 화살표 함수(Arrow Function)로 작성할 수 있으며, 짧은 코드로 작성할 수 있다는 장점이 있다.
  • 예를 들어, 한 줄로 반환하는 경우, @return@ 키워드를 생략할 수 있다.
const MyComponent = () => ( ... )

 

  • 컴포넌트 선언과 동시에 @export default@ 할 수 없다.
    • 컴포넌트 선언 후, @export default@를 따로 지정해야 한다.
const MyComponent = () => {}
export default MyComponent
  • @const@로 선언된 화살표 함수는 호이스팅(Hoisting)되지 않으므로, 사용 전에 반드시 선언해야 한다.
const App = () => (
    <>
      <MyComponent /> // 에러 발생
      <AlsoMyComponent /> // 에러 발생
    </>
)
const MyComponent = () => {}
const AlsoMyComponent = () => {}

 

② 함수 선언 방식

function MyComponent() {
    return(
      ..
    )
}

 

  • 컴포넌트를 선언하면서 바로 @export default@ 할 수 있다.
export default function MyComponent() {}

 

  • @function@ 문법으로 작성된 함수는 호이스팅(Hoisting)이 가능하여, 선언된 위치에 관계없이 파일 상단으로 끌어올려져 사용될 수 있다.
const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
function MyComponent() {}
function AlsoMyComponent() {}

 

컴포넌트가 호이스팅이 필요할 경우, 주로 함수 선언 방식을 사용한다.

 

참고 사이트

 

React functional components: const vs. function

Today I was wondering if there is any real difference in declaring a new component with the const arrow function syntax and function syntax. Tldr: Hoisting, I guess?

dev.to

 

728x90
728x90