LoginSignup
33
29

More than 5 years have passed since last update.

React Stateless Functional Componentを使うといい9つのポイント!(Class Based との違い)

Last updated at Posted at 2017-07-26

それではいきます。

1 Classが必要ない

constructorをつかわなくてもいいし、コードがシンプルになる。

2 thisが必要ない

class based componentではTHISが必要だけど、functional componentではthisがいらない。thisって混乱しやすいから使わなくてもいいのはとっても楽!

// With THIS
<a onClick = {this.sayHi.bind(this)}>Say Hi</a>

// Without This
<a onClick = {sayHi}>Say Hi</a>

ちなみに、bindはstatelessのコンポーネントの場合は必要ない。

3 UIに特化できる

Stateless function componentはpresentational componentsにとって都合がいい。presentational componentというのはふるまいよりもUIに特化したコンポーネント。presentational componentでは状態を保持しない。そのため、このコンポーネント内では状態を気にする必要はない。そのかわり、親のコンポーネントで状態を保持し管理する必要がある。

4 短文ですむ

stateless functional componentにすると通常よりも最大20%コードが減る。

statefulComponent.js
import React from 'react';

default export class helloWorld extends React.Component {
  render() {
    return (
      <div>{`Hi ${name}`}</div>
    )
  };
};

statelessComponent.js
import React from 'react';

default const HelloWorld = ({name}) => (
  <div>{`Hi ${name}`}</div>
);

5 コードがより完結する

stateless functional componentを使うと、その時点で使用するデータはシンプルなargumentsに限定されるため、シンプルでより完結したコードになる。

6 バグの修正がらくだしバグを防げる

class based componentは複雑になりやすく、どこを参照しているのかわからなくなったり、どのコンポーネントからデータを持ってきているのか混乱を起こしやすい。一方、stateless componentだと明らかにどのfunctional componentとargumentsと伝達されたのかがわかりやすい。バグを防げるし、バグが起こった時も修正をしやすい。

7 高い解読性

stateless functional componentはシンプルなので理解しやすい。たとえfunctionがネストされていてもその中はシンプル。

8 テストのしやすさ

functionはシンプルでテストの宣言もとてもストレート。独立してテストができ、モックも必要がなく、トリッキーなテストの技術も必要ない。

9 パフォーマンス性

パフォーマンスが高く、ライフサクルについて心配する必要もない。

まとめ

上記の理由から、可能な時はstateless functional componentsを使うよう努力するのが賢明といえる。

個人の感想

functional componentsをできるだけ使うべきという意見もあるが、大は小をかねるの考えでいくなら、1ファイル1つ、class based componentを作り、そこにfunctionを加えたい場合はstateless functional componentを作るという考えもあるのでは。functional componentを作ってからstateを使用する必要性に迫られて書き直すのも手間かかりそう。
個人的には、1ファイル1class based component、stateが不必要なことが明確な場合はstateless functional componentを使いたい。

引用
https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc

33
29
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
33
29