0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactの Fast Refresh 機能

Last updated at Posted at 2025-01-20

Fast Refresh 機能

Fast Refreshは、React開発中にコードを編集した際に、状態を保持しつつ画面を素早く更新する仕組みであり、開発体験を向上させるためのいくつかの利点がある。

利点1. リアルタイムでの即時更新

Fast Refreshを使うと、Reactコンポーネントのコードを編集するたびに、画面が即座に更新されます。これにより、以下が可能になります

  • 素早いフィードバック
    コードを保存した直後に、変更内容がブラウザ上で確認できます。

  • リロード不要
    ページ全体のリロードを必要とせず、変更箇所だけが更新されるため、開発効率が大幅に向上します。

利点2. コンポーネントの状態を保持

ページ全体のリロードではなく、コンポーネント単位で更新が行われるため、コンポーネントの状態が保持されます。


// フォームに入力したデータや、チェックボックスの選択状態などが保存されたまま、
// スタイルやロジックの修正結果を確認できます。
function Counter() {
  const [count, setCount] = React.useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Fast Refresh 機能が正常に動作しないコードがある

特定の要件を満たさないコードでは動作しない場合があります。

要件1. コンポーネント以外のエクスポートがある

定数や関数が同じファイルでエクスポートされている。

要件2. エクスポートの形が複雑

デフォルトエクスポートや名前付きエクスポートが混在している場合。

// このようなファイル構成が問題となる可能性があります

// 定数やユーティリティ関数をエクスポート
export const MY_CONSTANT = 42;

export function helperFunction() {
  return 'Hello';
}

// Reactコンポーネントをエクスポート
export default function MyComponent() {
  return <div>My Component</div>;
}

Fast Refresh機能が正常に機能しないときに発生するワーニング

Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components (react-refresh/only-export-components)

直訳
高速リフレッシュは、ファイルがコンポーネントのみをエクスポートする場合にのみ機能します。コンポーネント間で定数または関数を共有するには、新しいファイルを使用します (react-refresh/only-export-components)

解決方法

方法 1: コンポーネントとその他のロジックを分ける

Reactコンポーネント以外のエクスポート(定数や関数など)は別のファイルに分けることで解決できます。

helper.ts
export const MY_CONSTANT = 42;

export function helperFunction() {
    return 'Hello';
}
MyComponent.tsx

import { MY_CONSTANT, helperFunction } from './helpers';

export default function MyComponent() {
    console.log(MY_CONSTANT, helperFunction());
    return <div>My Component</div>;
}

方法 2: エクスポートを統一

同じファイル内にどうしてもコンポーネントとその他のロジックを含める場合は、すべてを名前付きエクスポートに統一します。

ただし、この方法はファイル分割に比べてFast Refreshの恩恵を受けにくい場合があります。

export const MY_CONSTANT = 42;

export function helperFunction() {
    return 'Hello';
}

// Reactコンポーネントも名前付きエクスポート
export function MyComponent() {
    return <div>My Component</div>;
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?