LoginSignup
0
2

React クラスコンポーネントのアンチパターン【初心者向け解説】

Posted at

Reactを使って開発を進める際、特定の方法が問題を引き起こす可能性があることを理解することは重要です。
これらは「アンチパターン」と呼ばれ、避けるべきプラクティスを示しています。
今回は、Reactのクラスコンポーネントに関連したアンチパターンをいくつか紹介します。

1. 不要なStateを持つ

Reactのクラスコンポーネントにおいて、propsから直接導出できる値をステートとして保持することは避けるべきです。ステートは通常、時間経過に伴って変更が発生するデータを表現するためのものです。

アンチパターン:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: this.props.name,
    };
  }

  //...
}

2. 直接ステートを変更する

Reactのステートは、this.setState()メソッドを通じて間接的に変更するべきです。これはReactがステートの変更を追跡し、再レンダリングを行うために必要です。

アンチパターン:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  incrementCount() {
    this.state.count += 1; // 間違い!
  }

  //...
}

3. ライフサイクルメソッドの誤用

ライフサイクルメソッドは特定のタイミングで実行されるものですが、それぞれが持つ特性を理解せずに使用すると予期しない問題を引き起こすことがあります。たとえば、componentDidUpdate内でステートを更新する場合、無限ループを引き起こす可能性があります。

アンチパターン:

class MyComponent extends React.Component {
  //...

  componentDidUpdate() {
    this.setState({ count: this.state.count + 1 }); // 間違い!
  }

  //...
}

まとめ

これらのアンチパターンは、Reactのクラスコンポーネントを使用する際に避けるべき一部の点を示しています。これらを理解し、適切なパターンを採用することで、バグの少ない、保守性の高いコードを書くことができます。

0
2
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
0
2