>  기사  >  웹 프론트엔드  >  종합 가이드에 반응하세요

종합 가이드에 반응하세요

WBOY
WBOY원래의
2024-08-07 01:45:43350검색

React  A Comprehensive Guide

React 19가 왔습니다! ? 이 글에서는 React 19의 새로운 기능과 개선 사항을 살펴보겠습니다. 자세히 살펴보겠습니다!

React 19의 새로운 기능

React 팀의 최신 주요 릴리스인 React 19에는 개발 프로세스를 더욱 효율적으로 만들고 결과 애플리케이션을 더 빠르고 강력하게 만들기 위해 설계된 여러 가지 획기적인 기능과 향상된 기능이 포함되어 있습니다. 이번 릴리스는 이전 버전이 구축한 강력한 기반을 계속해서 구축하여 핵심 프레임워크에 대한 중요한 업데이트를 도입합니다. 이 블로그에서는 새로운 React 컴파일러, 서버 구성 요소 및 서버 작업, 새로운 후크 및 API 등을 포함하여 React 19의 주요 기능을 살펴보겠습니다!

반응 컴파일러

React 19의 가장 흥미로운 기능 중 하나는 React Fizz라고도 알려진 새로운 React Compiler입니다. 이 컴파일러는 매우 효율적인 JavaScript 코드를 생성하여 React 애플리케이션의 성능을 최적화하도록 설계되었습니다. React Compiler는 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의 많은 규칙을 정적으로 확인할 수 있으며 오류가 감지되면 안전하게 컴파일을 건너뜁니다.

서버 구성 요소 및 서버 작업

서버 구성 요소는 빌드 시 실행되어 파일 시스템에서 읽거나 정적 콘텐츠를 가져올 수 있으므로 웹 서버가 필요하지 않습니다. 예를 들어 콘텐츠 관리 시스템에서 정적 데이터를 읽어야 할 수 있습니다.

서버가 없는 서버 구성 요소

서버 구성 요소가 없으면 효과를 사용하여 클라이언트에서 정적 데이터를 가져오는 것이 일반적입니다.

// 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.

위 내용은 종합 가이드에 반응하세요의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.