mcpField
R
react-19

react-19

github.com/gentleman-programming开发661268 次安装32 周前更新
代码仓库

关于 react-19

面向 React 开发者的 React 19 开发技能,涵盖编译器优化、Server Components、Hooks、Actions、导入方式与 ref 用法。

主要功能

  1. 01React Compiler 优化指导
  2. 02Server Components 优先模式
  3. 03React 19 use() 与 Actions
  4. 04具名导入规范
  5. 05将 ref 作为属性使用

适用场景

  1. 01在项目中采用 React 19 规范
  2. 02判断何时使用客户端组件
  3. 03处理 Promise 与表单 Actions
  4. 04将组件改为使用 ref 属性

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/gentleman-programming/gentleman-skills --skill react-19

安装后在 Claude Code 中输入/react-19确认已加载。

详细介绍

不进行手动记忆化(必需)

// ✅ React Compiler handles optimization automatically
function Component({ items }) {
  const filtered = items.filter(x => x.active);
  const sorted = filtered.sort((a, b) => a.name.localeCompare(b.name));

  const handleClick = (id) => {
    console.log(id);
  };

  return <List items={sorted} onClick={handleClick} />;
}

// ❌ NEVER: Manual memoization
const filtered = useMemo(() => items.filter(x => x.active), [items]);
const handleClick = useCallback((id) => console.log(id), []);

导入(必需)

// ✅ ALWAYS: Named imports
import { useState, useEffect, useRef } from "react";

// ❌ NEVER
import React from "react";
import * as React from "react";

优先使用服务端组件

// ✅ Server Component (default) - no directive
export default async function Page() {
  const data = await fetchData();
  return <ClientComponent data={data} />;
}

// ✅ Client Component - only when needed
"use client";
export function Interactive() {
  const [state, setState] = useState(false);
  return <button onClick={() => setState(!state)}>Toggle</button>;
}

何时使用 "use client"

  • useState、useEffect、useRef、useContext
  • 事件处理程序(onClick、onChange)
  • 浏览器 API(window、localStorage)

use() Hook

import { use } from "react";

// Read promises (suspends until resolved)
function Comments({ promise }) {
  const comments = use(promise);
  return comments.map(c => <div key={c.id}>{c.text}</div>);
}

// Conditional context (not possible with useContext!)
function Theme({ showTheme }) {
  if (showTheme) {
    const theme = use(ThemeContext);
    return <div style={{ color: theme.primary }}>Themed</div>;
  }
  return <div>Plain</div>;
}

Actions 与 useActionState

"use server";
async function submitForm(formData: FormData) {
  await saveToDatabase(formData);
  revalidatePath("/");
}

// With pending state
import { useActionState } from "react";

function Form() {
  const [state, action, isPending] = useActionState(submitForm, null);
  return (
    <form action={action}>
      <button disabled={isPending}>
        {isPending ? "Saving..." : "Save"}
      </button>
    </form>
  );
}

将 ref 作为属性(无需 forwardRef)

// ✅ React 19: ref is just a prop
function Input({ ref, ...props }) {
  return <input ref={ref} {...props} />;
}

// ❌ Old way (unnecessary now)
const Input = forwardRef((props, ref) => <input ref={ref} {...props} />);

关键词

react、react 19、编译器、useMemo、useCallback、服务端组件、use hook

评论

支持 Markdown