ホームページ  >  記事  >  ウェブフロントエンド  >  React と React (RC): 主な違いと移行のヒントと例

React と React (RC): 主な違いと移行のヒントと例

WBOY
WBOYオリジナル
2024-09-03 14:21:29955ブラウズ

React vs React (RC): Key Differences and Migration Tips with Examples

ユーザー インターフェイスを構築するための人気のある JavaScript ライブラリである React は、新しいリリースがリリースされるたびに進化し続けています。このブログ投稿では、React 18 と次期 React 19 (現在リリース候補段階) の主な違いを調査し、新機能の例を示し、React with Vite を使用する開発者向けの移行ヒントを提供します。

目次

  1. はじめに
  2. React 19 の現在のステータス
  3. 例との主な違い
    • サーバー側レンダリングの改善
    • 強化された同時レンダリング
    • 新しいフックと API
    • パフォーマンスの最適化
  4. 移行のヒント
  5. Vite で React 19 RC を使用する
  6. 結論

導入

React 18 では、自動バッチ処理、同時レンダリング用の新しい API、トランジションなどの重要な変更が導入されました。 React 19 はまだ開発中ですが、これらの基盤の上にさらなる改善と新機能を組み込むことを目指しています。

React 19 の現状

2024 年 9 月の時点で、React 19 はリリース候補 (RC) 段階にあります。機能は完備されており、テストの準備ができていますが、運用環境での使用はまだ推奨されていません。機能と API は最終リリースまでに変更される可能性があります。

例との主な違い

該当する場合は例と React 18 との比較を示しながら、React 19 で期待される主な改善点と新機能について詳しく見ていきましょう。

サーバー側レンダリングの改善

  1. 強化ストリーミング SSR

React 19 は、ストリーミング SSR をさらに最適化することを目的としています。 API は React 18 と同様のままですが、パフォーマンスの向上は顕著であるはずです。

例 (React 18 と 19 の両方で同様):

// server.js
import { renderToPipeableStream } from 'react-dom/server';

app.get('/', (req, res) => {
  const { pipe } = renderToPipeableStream(<App />, {
    bootstrapScripts: ['/client.js'],
    onShellReady() {
      res.statusCode = 200;
      res.setHeader('Content-type', 'text/html');
      pipe(res);
    },
  });
});
  1. 洗練された選択的水分補給

React 19 は、React 18 で導入された選択的水和を改善すると期待されています。

React 19 の例 (構文は React 18 に似ていますが、動作が改善されています):

import { Suspense } from 'react';

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <MainContent />
      <Suspense fallback={<SidebarLoading />}>
        <Sidebar />
      </Suspense>
    </Suspense>
  );
}

この例では、React 19 はサイドバーの読み込み中に MainContent コンポーネントを優先して、よりスムーズなハイドレーションを提供する可能性があります。

  1. サーバーコンポーネント

React 19 には、サーバー コンポーネントのより安定した実装が含まれる予定です。

React 19 のサーバー コンポーネントの例:

// Note: This syntax is speculative and may change
'use server';

import { db } from './database';

async function UserProfile({ userId }) {
  const user = await db.user.findUnique({ where: { id: userId } });
  return <div>{user.name}</div>;
}

export default UserProfile;

この例では、UserProfile コンポーネントがサーバー上で実行され、機密情報をクライアントに公開することなくデータベースに直接アクセスできます。

強化された同時レンダリング

  1. 改良されたサスペンス

React 19 では、フォールバック処理が改善されてサスペンス コンポーネントが強化されています。

React 18 の例:

function ProfilePage({ userId }) {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <ProfileDetails userId={userId} />
      <Suspense fallback={<h2>Loading posts...</h2>}>
        <ProfileTimeline userId={userId} />
      </Suspense>
    </Suspense>
  );
}

React 19 の潜在的な改善 (推測):

function ProfilePage({ userId }) {
  return (
    <Suspense
      fallback={<h1>Loading profile...</h1>}
      primaryContent={<ProfileDetails userId={userId} />}
    >
      <ProfileTimeline userId={userId} />
    </Suspense>
  );
}

この推測的な React 19 の例では、primaryContent プロパティを使用して、開発者が読み込み中にどのコンテンツを優先するかを指定できる可能性があります。

  1. 拡張自動レンダリングバッチ処理

React 18 では、setState とフックの自動バッチ処理が導入されました。 React 19 では、これをさらに多くのシナリオに拡張する可能性があります。

React 18 の例:

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(c => c + 1); // Does not re-render yet
    setCount(c => c + 1); // Does not re-render yet
    // React will only re-render once at the end (that's batching!)
  }

  return <button onClick={handleClick}>{count}</button>;
}

React 19 では、このバッチ処理がさらに多くのシナリオに拡張される可能性があり、非同期操作が含まれる可能性があります。

  1. 微調整された優先順位ベースのレンダリング

React 19 では、レンダリングの優先順位をより詳細に制御できるようになる可能性があります。

潜在的な React 19 の例 (推測):

import { useDeferredValue, startTransition } from 'react';

function SearchResults({ query }) {
  const deferredQuery = useDeferredValue(query);

  return (
    <>
      <div>Searching for: {query}</div>
      <Suspense fallback={<Spinner />}>
        <Results query={deferredQuery} />
      </Suspense>
    </>
  );
}

function handleSearch(input) {
  startTransition(() => {
    setSearchQuery(input);
  });
}

この例では、React 19 は、ユーザー入力に応じて UI のさまざまな部分がどのように更新されるかをより詳細に制御できる可能性があります。

新しいフックと API

  1. イベントフックを使用

React 19 では、古いクロージャの問題を解決するために useEvent フックが導入される予定です。

React 18 の問題:

function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

  function handleSend() {
    // This might use a stale `roomId` if the component re-renders
    sendMessage(roomId, message);
  }

  return <button onClick={handleSend}>Send</button>;
}

useEvent を使用した潜在的な React 19 ソリューション:

function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

  const handleSend = useEvent(() => {
    // This will always use the current `roomId`
    sendMessage(roomId, message);
  });

  return <button onClick={handleSend}>Send</button>;
}
  1. コンテキスト API の改善

React 19 には、パフォーマンスの問題に対処するための Context API の改善が含まれる可能性があります。

React 18 の例:

const ThemeContext = React.createContext('light');

function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={theme}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  );
}

React 19 の潜在的な改善 (推測):

const ThemeContext = React.createContext('light', (prev, next) => prev === next);

function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={theme}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  );
}

この推測的な例では、不必要な再レンダリングを防ぐためにコンテキストに比較関数が含まれている可能性があります。

パフォーマンスの最適化

多くのパフォーマンスの最適化は内部で行われますが、一部は開発者に見える場合があります:

  1. 差分アルゴリズムの改善

React 19 は調整プロセスを最適化することが期待されています。これにはコードを変更する必要はないかもしれませんが、複雑な UI の更新が速くなる可能性があります。

  1. Memory Usage Improvements

React 19 may include optimizations to reduce memory usage. Again, this might not require code changes but could improve performance, especially for large applications.

  1. Better Tree Shaking

React 19 might improve tree shaking capabilities. This could result in smaller bundle sizes when using build tools like Vite.

Example vite.config.js that might better leverage React 19's tree shaking:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor';
          }
        }
      }
    }
  }
})

Migration Tips

  1. Stay Informed: Keep an eye on the official React blog and documentation for updates.
  2. Experiment in Non-Production Environments: Try the React 19 RC in development or staging environments.
  3. Review Deprecated APIs: Check the documentation for any deprecated APIs and plan updates accordingly.
  4. Leverage New Features Gradually: Implement new features in non-critical parts of your application first.
  5. Optimize Rendering: Review your component structure and use of Suspense boundaries.
  6. Comprehensive Testing: Thoroughly test your application, especially areas relying on React's internal APIs.

Using React 19 RC with Vite

To experiment with the React 19 Release Candidate using Vite:

  1. Create a new Vite project:
   npm create vite@latest my-react-19-rc-app -- --template react
  1. Navigate to the project directory:
   cd my-react-19-rc-app
  1. Install the React 19 RC versions:
   npm install react@rc react-dom@rc
  1. Update your vite.config.js:
   import { defineConfig } from 'vite'
   import react from '@vitejs/plugin-react'

   export default defineConfig({
     plugins: [react()],
     esbuild: {
       jsxInject: `import React from 'react'`
     },
     optimizeDeps: {
       include: ['react', 'react-dom']
     }
   })
  1. Start the development server:
   npm run dev

Remember, using the RC version in production is not recommended.

Conclusion

While React 19 is still in the Release Candidate stage, it promises exciting improvements and new features. From enhanced server-side rendering to new hooks and performance optimizations, there's much to explore in React 19.

As the release date approaches, stay tuned to the official React documentation and community resources for the most up-to-date information. By staying informed and gradually adopting new features as they become stable, you'll be well-positioned to leverage the improvements in React 19 for your projects.

以上がReact と React (RC): 主な違いと移行のヒントと例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。