Navigation

ReactのError Boundaryを使ってエラーをキャッチし、ユーザーフレンドリーなエラーページを表示する方法

📅 7月 9, 2025
👤
1 min read

ReactのError Boundaryを使ってエラーをキャッチし、ユーザーフレンドリーなエラーページを表示する方法

概要

ReactのError Boundaryは、コンポーネントの階層構造内でエラーをキャッチし、ユーザーにフレンドリーなエラーページを表示するための機能です。この機能を使用することで、アプリケーション全体をクラッシュさせることなくエラーを処理できます。

**なぜこの技術/パターンが必要なのか:**

Reactアプリケーションでは、エラーが発生した際にクラッシュするとユーザーエクスペリエンスが悪化します。Error Boundaryを使用することで、エラーのスコープを限定し、ユーザーに適切なエラーメッセージを表示することができます。

**解決する問題やユースケース:**

  • アプリケーション全体のクラッシュを防ぎたい場合
  • ユーザーフレンドリーなエラーメッセージを表示したい場合

**前提知識と必要な依存関係:**

  • Reactの基本知識
  • JavaScript/TypeScriptの知識
  • React v16以降が必要

基本実装


import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

TypeScript型定義


interface Props {
  children: React.ReactNode;
}

interface State {
  hasError: boolean;
}

テストコード


import { render } from '@testing-library/react';
import ErrorBoundary from './ErrorBoundary';

test('should render error message when error occurs', () => {
  const ErrorComponent = () => {
    throw new Error('Test Error');
  };

  const { getByText } = render(
    <ErrorBoundary>
      <ErrorComponent />
    </ErrorBoundary>
  );

  expect(getByText('Something went wrong.')).toBeInTheDocument();
});

パフォーマンス最適化

Error Boundaryはパフォーマンスに大きな影響を与えるわけではありませんが、不要な再レンダリングを防ぐために適切に使用することが重要です。

実践的な応用例


const App = () => (
  <ErrorBoundary>
    <MainComponent />
  </ErrorBoundary>
);

関連技術・参考情報

  • [React 公式ドキュメント – Error Boundaries](https://reactjs.org/docs/error-boundaries.html)

この記事では、ReactのError Boundaryを使用してエラーをキャッチし、ユーザーフレンドリーなエラーページを表示する方法について解説しました。エラーハンドリングはアプリケーションの信頼性とユーザーエクスペリエンス向上に重要な役割を果たすため、適切に活用することが重要です。

← Back to React