ReactのFunction ComponentとHooks

reacttypescriptweb

久々にcreate-react-appを実行したら コンポーネントがReact.ComponentのクラスではなくFunction Componentになっていた。

Function Component

Function Componentは関数で書かれるStateを持たないコンポーネントで、 簡潔に書けるだけではなくReact.createElement()と比べて45%くらい速いらしい。

45% Faster React Functional Components, Now – Missive App – Medium

const App: React.FC = () => {
  return (
    <div className="App">
      {FunctionalComponent({title: "HELLO FC"})}
    </div>
  );
}

interface Props {
  title: string
}

const FunctionalComponent: React.FC<Props> = (props) => {
  return (
    <div>
      {props.title}
    </div>
  );
}

v16.6でリリースされた React.memo()を使うと PureComponent のようにpropsが変わらない場合は再レンダリングさせなくすることができる。

const App: React.FC = () => {
  return (
    <div className="App">
      <FunctionalComponent title="HELLO FC" />
    </div>
  );
}

interface Props {
  title: string
}

const FunctionalComponent = React.memo((props) => {
  return (
    <div>
      {props.title}
    </div>
  );
})

React Hooks

Function ComponentはClass Componentのようにstateを持ったり、componentDidMount()といった ライフサイクルメソッドを生やすことができなかったが、 v16.8でリリースされた React Hooksによってこれらを 実現できるようになった。

React HooksというのはReactの機能と接続する関数で、 次のような組み込みのHooksに加えて 独自のHooksを作ることもでき、 例えばreact-reduxにもHooks APIがある。

Reactが管理するstateの値と、変更する関数を返す。

副作用を起こす関数をrender後に非同期で実行させる。 クリーンアップ処理の関数を返すことができ、Unmount時や次回の副作用の前に実行される。

import React, { useState, useEffect } from 'react';

const FunctionalComponent: React.FC<Props> = (props) => {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
    // Specify how to clean up after this effect
    return () => {
      console.log("Clean up")
    }
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useEffect()の第二引数に配列を渡すと、そこに含まれる値が変わらない場合は 実行をスキップさせることができる。 空の配列を渡すと最初の1度しか実行されない。

参考

Functional Component と PureComponentの違い・使い分け - Qiita