LoginSignup
2
0

More than 3 years have passed since last update.

【React】関数コンポーネントとクラスコンポーネント

Posted at

関数コンポーネント(Function Components)

  • TypeScriptでは関数コンポーネントの型は React.FunctionComponent インタフェースとして定義されている
    -> エイリアスとして定義されている React.FC を使用可能
/components/Hello.tsx
import * as React from 'react';

// Hello コンポーネントの定義
export const Hello: React.FC = () => {
  return <h1>Hello</h1>
};
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Hello } from './components/Hello';

ReactDOM.render(<Hello />, document.getElementById('root'));

クラスコンポーネント(Class Components)

  • TypeScriptでは React.Component を継承し、 render() メソッドを実装する
/components/Hello.tsx
import * as React from 'react';

export class Hello extends React.Component<Props> {
  public render(): JSX.Element {
    return <h1>Hello</h1>
  }
};
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Hello } from './components/Hello';

ReactDOM.render(<Hello />, document.getElementById('root'));

関数コンポーネントとクラスコンポーネントの違い

state(状態管理)とLifecycle methodを使用可能か

Hooks導入以前 Hooks導入後
クラスコンポーネント 使用可能 使用可能
関数コンポーネント 使用不可 使用可能

関数コンポーネントとクラスコンポーネントのどちらを使用するべきか

結論

  • 関数コンポーネントを推奨

理由

  • コードを簡潔に書けるため
    • this を使う必要がなくなる
    • constructor render が不要になる
  • 同一ロジックが混入しにくいため
    • ライフサイクルメソッドに分割する必要がない
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0