내 세상

[React] Class Component / Function Component / Arrow Function 본문

Technical/React

[React] Class Component / Function Component / Arrow Function

sga8 2020. 5. 11. 16:45
728x90
반응형

React Official Reference에서는 Function Component + Hooks 사용을 권장함.

 

  Class component Function component
     
장점 render 함수 필수

선언이 편리함.
메모리 자원 덜 사용함.
Build/Deploy 후 결과물 파일 크기가 더 작음.
단점   state / Lifecycle API 사용 불가능.
→ React v16.8 이후 Hooks 도입으로 해결됨.

 


화살표 함수(Arrow Function)

  - ES6 문법에서 함수를 표현하는 새로운 방식.

  - 기존 function과 사용 용도가 조금 다름. 주로 함수를 파라미터로 전달할 때 유용함.

  일반 함수(Normal Function) 화살표 함수(Arrow Function)
샘플 코드 function testFunc1() {
  this.name = "AAA";
  return {
    name : "BBB",
    test: function() {
      console.log(this.name);
    }
  }
}

let testFunc1 = new testFunc1();
testFunc1.test();
function testFunc2() {
  this.name = "AAA";
  return {
    name : "BBB",
    test: function() {
      console.log(this.name);
    }
  }
}

let testFunc2 = new testFunc2();
testFunc2.test();
결과 BBB AAA
이유 자신이 종속된 객체를 this로 가리킴. 자신이 종속된 인스턴스를 this로 가리킴.

 

728x90
반응형