기록하는 개발자

<React 파헤치기-14> 컴포넌트 - 6.클래스형 컴포넌트와 함수형 컴포넌트 본문

Web/React

<React 파헤치기-14> 컴포넌트 - 6.클래스형 컴포넌트와 함수형 컴포넌트

밍맹030 2021. 12. 27. 16:22
728x90

react 컴포넌트 선언하는 방식에는 클래스형 컴포넌트와 함수형 컴포넌트가 있다.

그렇다면 두 방식의 차이점은 무엇일까?

 

1. 선언 방식

 

클래스형 컴포넌트

import React, {Component} from 'react';

class App extends Component {
  render() {
    const Hello = 'hello';
    return <div className="hello">{Hello}</div>
  }
}

export default App;

1. class 키워드가 필요하며, Component 상속을 받아야한다.

2. render() 메소드가 반드시 필요하다.

3. 함수형보다 메모리 자원을 더 많이 사용한다.

4. state, lifeCycle 관련 기능(생명주기함수)사용이 가능하다.

5. 함수형보다 메모리 자원을 더 많이 사용한다.

6. 임의 메소드를 정의할 수 있다.

 

 

함수형 컴포넌트

import React from 'react';
import './App.css';

function App() {
  const Hello = 'hello';
  return <div className = "hello">{Hello}</div>
}

export default App;

1. state, lifeCycle 관련 기능사용 불가능한 대신, 이를 Hook을 통해 해결한다.

2. 클래스형보다 메모지 자원을 덜 사용한다.

3. 컴포넌트 선언이 편하다.

 

 

2. state 사용의 차이

 state : 함수 내부에서 변경이 가능한 값

 

 

클래스형 컴포넌트

 

 

-1) constructor 안에서 this.state 초기 값 설정이 가능하다.

constructor(props){
    super(props);
    this.state={
        icecream : ["vanilla", "chocolate", "lemon"],
        favoriteFlavor : "vanilla",
    };
}

-2) constructor 없이 바로 state 초기값 설정도 가능하다.

class Icecream extends Component{
    state={
        icecream : ["vanilla", "chocolate", "lemon"],
        favoriteFlavor : "vanilla",
    };
}

-3) 클래스형 컴포넌트의 state는 객체 형태이다.

state={ 
    icecream : ["vanilla", "chocolate", "lemon"],
    favoriteFlavor : "vanilla",
};

-4) this.setState 함수로 state의 값을 변경할 수 있다.

onClick = { () => {
    this.setState({num : num+1});
}}

 

함수형 컴포넌트

 

함수형 컴포넌트에서는 Hook인 useState 함수로 state를 관리한다.

useState 함수를 호출하면 배열이 반환되는데

이때, 배열의 첫 번째 원소현재 상태, 두 번째 원소상태를 바꾸어 주는 함수 이다.

const [ msg, setMsg ] = useState("hello!");

 

3. props 사용의 차이

 props

 컴포넌트의 속성을 설정 할 때 사용하는 요소이다.

 읽기 전용으로 컴포넌트 자체 props를 수정하면 안된다. 

 

클래스형 컴포넌트

- this.props로 통해 값을 불러올 수 있다.

class Icecream extends Component{
    render(){
        const { color, coffee, tea } = this.props;
        return(
            <div>
                my favorite color is {color}
                I love {coffee} but I'm weak to caffeine
                so after 5pm I usually drink {tea}
            </div>
        );
    }
}

 

함수형 컴포넌트

- props를 불러올 필요 없이 바로 호출 가능하다.

const Icecream = ({ color, coffee, tea }) =>{
    return(
        <div>
            my favorite color is {color}
            I love {coffee} but I'm weak to caffeine
            so after 5pm I usually drink {tea}
        </div>
    );
}

 

728x90