React 19 來了! ?在本文中,我們將探索 React 19 中的新功能和改進。讓我們開始吧!
React 19 是 React 團隊的最新主要版本,具有多項突破性功能和增強功能,旨在使開發過程更加高效,並使生成的應用程式更快、更強大。該版本繼續建立在其前身奠定的堅實基礎上,對核心框架進行了重大更新。在這篇部落格中,我們將探索 React 19 的主要功能,包括新的 React 編譯器、伺服器元件和伺服器操作、新的鉤子和 API 等等!
React 19 中最令人興奮的功能之一是新的 React 編譯器,也稱為 React Fizz。該編譯器旨在透過產生高效的 JavaScript 程式碼來優化 React 應用程式的效能。 React 編譯器將您的 JSX 和 JavaScript 程式碼轉換為高度最佳化的 JavaScript,可以更快地執行、更好的記憶體使用和更少的開銷。這仍處於實驗模式,但它是一個很有前途的功能,可能會改變 React 開發人員的遊戲規則。它使用純 JavaScript,並理解 React 規則,因此您無需重寫任何程式碼即可使用它。
編譯器做什麼?
為了優化應用程序,React Compiler會自動記憶組件和鉤子,並優化渲染過程。這意味著React只會重新渲染實際改變的元件,而不是重新渲染整個元件樹。這可以顯著提高效能,特別是對於大型複雜的應用程式。
如果您的程式碼庫已經被很好地記住了,您可能不會期望看到編譯器的重大效能改進。然而,在實踐中,手動記住導致效能問題的正確依賴是很棘手的。編譯器可以幫助你。
編譯器假設什麼?
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 會向伺服器發送請求來執行該函數,並傳回結果。
伺服器操作可以在伺服器元件中建立並作為道具傳遞給客戶端元件,也可以在客戶端元件中匯入和使用。
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} /> }
Besides the React Compiler and Server Components, React 19 introduces several new hooks and APIs that make it easier to build complex applications.
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.
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.
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.
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); // ...
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中文網其他相關文章!