리액트 네이티브에서 Hook을 사용하던중 

Only Call Hooks from React Functions

Don’t call Hooks from regular JavaScript functions. Instead, you can:

  • ✅ Call Hooks from React function components.
  • ✅ Call Hooks from custom Hooks (we’ll learn about them on the next page).

위와 같은 hook 규칙을 보고 이번 기회에 functional component와 class component의 차이에 대해 한번 짚고 넘어가야 겠다고 생각했다. 

 

[선언방식]

1) Class component

import React from "react";

class App extends React.Component {
  render() { return null }
}

export default App;

함수형 컴포넌트와 생성하는 형식의 차이를 보여주기 위해 아무 기능없이 null을 반환하는 간단한 Class component를 작성하였다. 

 

2-1) Functional component (표현식 = arrow function)

import { Text} from "react-native";

const App = () => {
  const bodyText = "This is not really a bird nest.";

return (
      <Text>{bodyText}</Text>
  );
};

export default APP;

 

2-2) Functional component (선언식)

import React from 'react';

function App() {
  const name = '리액트';
  return <div>{name}</div>;
}

export default App;

 

그래서! 차이점이 뭔데?!?!

1.과거에 훅이 도입되기 전에는 함수형 컴포넌트에서 state와 라이프사이클 API를 사용할 수 없다는 단점이 있었다. 

2.훅이 도입되고 함수형 컴포넌트에서 useState, useEffect 등 다양한 훅을 사용하여 state관리가 가능하다.

   훅은 오직 함수형 컴포넌트에서만 사용가능하다.(Hook's rules)

3.클래스 컴포넌트는 반드시 render가 필요하다.

 

결론 : 훅이 도입된 이후 함수형 컴포넌트가 선언하기 편하고 메모리 자원을 아낄 수 있어서 더 많이 사용되는 추세이다.

 

//클래스 컴포넌트에서 state사용

import React from "react";

class App extends React.Component {
  //consturctor를 사용하여 state 설정
  constructor(props) {
        super(props);
        //state의 초깃값 설정하기 
        this.state = {
            text : 'Hi'
        };
    }
  /*constructor 없이 간단하게 state설정
  state = {
  		text : 'Hi'
	}
  */
  render() { 
      const {text} = this.state;
      <h1>text</h1>
  }
}

export default App;