React の総合ガイド

WBOY
リリース: 2024-08-07 01:45:43
オリジナル
350 人が閲覧しました

React  A Comprehensive Guide

React 19 が登場しました! ?この記事では、React 19 の新機能と改善点について説明します。詳しく見ていきましょう!

React 19 の新機能

React チームによる最新のメジャー リリースである React 19 には、開発プロセスをより効率的にし、結果として得られるアプリケーションをより高速かつ強力にするために設計されたいくつかの画期的な機能と拡張機能が搭載されています。このリリースは、前任者によって築かれた強力な基盤の上に構築され続けており、コア フレームワークに大幅なアップデートが導入されています。このブログでは、新しい React コンパイラー、サーバー コンポーネントとサーバー アクション、新しいフックと API など、React 19 の主要な機能について説明します!

反応コンパイラ

React 19 の最もエキサイティングな機能の 1 つは、React Fizz としても知られる新しい React コンパイラーです。このコンパイラは、高効率の JavaScript コードを生成することで React アプリケーションのパフォーマンスを最適化するように設計されています。 React コンパイラーは、JSX および JavaScript コードを高度に最適化された JavaScript に変換し、メモリ使用率が向上し、オーバーヘッドが少なく、より高速に実行できるようにします。これはまだ実験モードですが、React 開発者にとって大きな変革をもたらす可能性が高い有望な機能です。これはプレーンな JavaScript で動作し、React のルールを理解するので、使用するためにコードを書き直す必要はありません。

コンパイラは何をしますか?

アプリケーションを最適化するために、React Compiler はコンポーネントとフックを自動的にメモ化し、レンダリング プロセスも最適化します。これは、React がコンポーネント ツリー全体を再レンダリングするのではなく、実際に変更されたコンポーネントのみを再レンダリングすることを意味します。これにより、特に大規模で複雑なアプリケーションの場合、パフォーマンスが大幅に向上する可能性があります。

コードベースがすでに十分にメモ化されている場合、コンパイラーによる大幅なパフォーマンスの向上は期待できないかもしれません。ただし、実際には、パフォーマンスの問題を引き起こす正しい依存関係を手動で正確にメモ化するのは困難です。コンパイラはそれを支援します。

コンパイラは何を想定していますか?

React Compiler はコードを次のように想定しています。

  • 有効なセマンティック JavaScript です
  • null 許容/オプションの値とプロパティが定義されているかどうかを、アクセスする前にテストします (たとえば、TypeScript を使用している場合は strictNullChecks を有効にすることによって)。つまり、 if (object.nullableProperty) { object.nullableProperty.foo } またはオプションの連鎖オブジェクトを使用します。 nullableProperty?.foo
  • React のルールに従います

React Compiler は、React のルールの多くを静的に検証でき、エラーを検出するとコンパイルを安全にスキップします。

サーバーコンポーネントとサーバーアクション

サーバー コンポーネントはビルド時に実行してファイル システムから読み取ったり、静的コンテンツをフェッチしたりできるため、Web サーバーは必要ありません。たとえば、コンテンツ管理システムから静的データを読み取りたい場合があります。

サーバーのないサーバーコンポーネント

サーバー コンポーネントがなければ、エフェクトを使用してクライアント上の静的データをフェッチするのが一般的です。

// bundle.js
import marked from 'marked'; // 35.9K (11.2K gzipped)
import sanitizeHtml from 'sanitize-html'; // 206K (63.3K gzipped)

function Page({page}) {
  const [content, setContent] = useState('');
  // NOTE: loads *after* first page render.
  useEffect(() => {
    fetch(`/api/content/${page}`).then((data) => {
      setContent(data.content);
    });
  }, [page]);

  return <div>{sanitizeHtml(marked(content))}</div>;
}
ログイン後にコピー

サーバー コンポーネントを使用すると、ビルド時に静的データをフェッチできます:

import marked from 'marked'; // Not included in bundle
import sanitizeHtml from 'sanitize-html'; // Not included in bundle

async function Page({page}) {
  // NOTE: loads *during* render, when the app is built.
  const content = await file.readFile(`${page}.md`);

  return <div>{sanitizeHtml(marked(content))}</div>;
}
ログイン後にコピー

レンダリングされた出力はキャッシュして静的に提供できるため、サーバーは JavaScript を実行する必要がありません。これは、特にモバイル デバイスのパフォーマンスに大きなメリットをもたらす可能性があります。アプリが読み込まれると、ネットワーク リクエストを待たずに、すぐにコンテンツを表示できます。

サーバーコンポーネントとサーバー

サーバー コンポーネントはサーバー上でも実行できます。これは、ユーザー固有のデータや頻繁に変更されるデータなど、静的ではないデータを取得する場合に便利です。たとえば、ユーザー固有のデータをデータベースからフェッチしたい場合がありますが、これは通常 useEffect フックを使用して実現されます:

// bundle.js
function Note({id}) {
  const [note, setNote] = useState('');
  // NOTE: loads *after* first render.
  useEffect(() => {
    fetch(`/api/notes/${id}`).then(data => {
      setNote(data.note);
    });
  }, [id]);

  return (
    <div>
      <Author id={note.authorId} />
      <p>{note}</p>
    </div>
  );
}

function Author({id}) {
  const [author, setAuthor] = useState('');
  // NOTE: loads *after* Note renders.
  // Causing an expensive client-server waterfall.
  useEffect(() => {
    fetch(`/api/authors/${id}`).then(data => {
      setAuthor(data.author);
    });
  }, [id]);

  return <span>By: {author.name}</span>;
}
ログイン後にコピー

サーバー コンポーネントを使用すると、データを読み取り、コンポーネント内でレンダリングできます。

import db from './database';

async function Note({id}) {
  // NOTE: loads *during* render.
  const note = await db.notes.get(id);
  return (
    <div>
      <Author id={note.authorId} />
      <p>{note}</p>
    </div>
  );
}

async function Author({id}) {
  // NOTE: loads *after* Note,
  // but is fast if data is co-located.
  const author = await db.authors.get(id);
  return <span>By: {author.name}</span>;
}
ログイン後にコピー

サーバー コンポーネントはサーバーから再フェッチすることで動的にすることができ、そこでデータにアクセスして再度レンダリングできるようになります。この新しいアプリケーション アーキテクチャは、サーバー中心のマルチページ アプリのシンプルな「リクエスト/レスポンス」メンタル モデルと、クライアント中心のシングルページ アプリのシームレスな対話性を組み合わせて、両方の長所を提供します。

サーバーアクション

サーバー アクションが「use server」ディレクティブで定義されている場合、フレームワークは自動的にサーバー関数への参照を作成し、その参照をクライアント コンポーネントに渡します。その関数がクライアントで呼び出されると、React はサーバーにリクエストを送信して関数を実行し、結果を返します。

サーバー アクションは、サーバー コンポーネントで作成して props としてクライアント コンポーネントに渡すことも、インポートしてクライアント コンポーネントで使用することもできます。

Creating a Server Action from a Server Component:

// Server Component
import Button from './Button';

function EmptyNote () {
  async function createNoteAction() {
    // Server Action
    'use server';

    await db.notes.create();
  }

  return <Button onClick={createNoteAction}/>;
}
ログイン後にコピー

When React renders the EmptyNote Server Component, it will create a reference to the createNoteAction function, and pass that reference to the Button Client Component. When the button is clicked, React will send a request to the server to execute the createNoteAction function with the reference provided:

"use client";

export default function Button({onClick}) { 
  console.log(onClick); 
  return <button onClick={onClick}>Create Empty Note</button>
}
ログイン後にコピー

Importing and using a Server Action in a Client Component:

Client Components can import Server Actions from files that use the "use server" directive:

"use server";

export async function createNoteAction() {
  await db.notes.create();
}
ログイン後にコピー

When the bundler builds the EmptyNote Client Component, it will create a reference to the createNoteAction function in the bundle. When the button is clicked, React will send a request to the server to execute the createNoteAction function using the reference provided:

"use client";
import {createNoteAction} from './actions';

function EmptyNote() {
  console.log(createNoteAction);
  // {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNoteAction'}
  <button onClick={createNoteAction} />
}
ログイン後にコピー

New Hooks and APIs

Besides the React Compiler and Server Components, React 19 introduces several new hooks and APIs that make it easier to build complex applications.

useOptimistic

The useOptimistic hook allows you to update the UI optimistically before the server responds. This can make your application feel more responsive and reduce the perceived latency. The hook takes a callback function that performs the optimistic update, and an optional configuration object that specifies the server request to send after the optimistic update.

useFormStatus

The useFormStatus hook allows you to track the status of a form, such as whether it is pristine, dirty, valid, or invalid. This can be useful for displaying feedback to the user, such as error messages or success messages.

useFormState

The useFormState hook allows you to manage the state of a form, such as the values of the form fields and the validity of the form. This can be useful for building complex forms with dynamic validation logic.

This hook requires two arguments: the initial form state and a validation function. The validation function takes the form state as input and returns an object with the validity of each form field.

The new use API

React 19 introduces a new use API that is a versatile way to read values from resources like Promises or context. The use API is similar to the useEffect hook, but it doesn't take a callback function. Instead, it returns the value of the resource, and re-renders the component when the value changes.

const value = use(resource);
ログイン後にコピー

Example:

import { use } from 'react';

function MessageComponent({ messagePromise }) {
  const message = use(messagePromise);
  const theme = use(ThemeContext);
  // ...
ログイン後にコピー

Conclusion - Should You Upgrade to React 19?

React 19 is a major release that introduces several groundbreaking features and enhancements to the core framework. The new React Compiler, Server Components, and Server Actions are designed to make the development process more efficient and the resulting applications faster and more powerful. The new hooks and APIs make it easier to build complex applications and improve the user experience. If you're already using React, upgrading to React 19 is definitely worth considering.

But at the same time it's important to note that React 19 is still in experimental mode, and some features may change before the final release. It's recommended to test your application with React 19 in a non-production environment before upgrading. If you're starting a new project, React 19 is a great choice, as it provides a solid foundation for building modern web applications.

以上がReact の総合ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!