3

React 18 Beta来了

 2 years ago
source link: https://segmentfault.com/a/1190000040966821
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

大家好,我卡颂。

经过React18工作组几个月工作,11月16日v18终于从Alpha版本更新到Beta版本。

本文会解释:

  • 这次更新带来的变化
  • 对开发者的影响
  • 如何安装v18 Beta
  • v18稳定版何时会来

带来的变化

经过与社区不断沟通,Beta版将有如下三个API变动:

  1. useSyncExternalStore将替代useMutableSource 用于订阅外部源,见:#86讨论

用法类似如下:

import {useSyncExternalStore} from 'react';

// 基础用法,getSnapshot返回一个缓存的值
const state = useSyncExternalStore(store.subscribe, store.getSnapshot);

// 根据数据字段,使用内联的getSnapshot返回缓存的数据
const selectedField = useSyncExternalStore(store.subscribe, () => store.getSnapshot().selectedField);
  1. useId用于在客户端与服务端之间产生唯一ID,避免SSR hydrate时元素不匹配,见#111讨论

用法类似如下:

function Checkbox() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Do you like React?</label>
      <input type="checkbox" name="react" id={id} />
    </>
  );
);
  1. useInsertionEffect用于插入全局DOM节点,见#110讨论

useInsertionEffect工作原理类似useLayoutEffect,区别在于回调执行时还不能访问ref中的DOM节点。

你可以在这个Hook内操作全局DOM节点(比如<style>或SVG<defs)。

操作CSS的库(比如CSS-IN-JS方案)可以用这个Hook插入全局<style>

用法类似如下:

function useCSS(rule) {
  useInsertionEffect(() => {
    if (!isInserted.has(rule)) {
      isInserted.add(rule);
      document.head.appendChild(getStyleForRule(rule));
    }
  });
  return rule;
}
function Component() {
  let className = useCSS(rule);
  return <div className={className} />;
}

至此,v18的特性已经完备,正式版发布之前不会再新增API

对开发者的影响

React团队已经在多个应用的生产环境测试了Beta版本几个月,并且相信他足够稳定。所以,开发者已经可以升级至v18 Beta版本。

Beta作为预发布版本,与最终的正式版的区别是:可能还有少许bug,但整体稳定。

社区中兼容v18的知名项目包括:

  • Next.js
  • Gatsby
  • React Redux
  • React Testing Library

安装Beta

安装命令如下:

# npm
npm install react@beta react-dom@beta
# yarn
yarn add react@beta react-dom@beta

稳定版何时回来

根据Andrew的回复,正式版最早发布时间可能会在22年1月底。

不管是新文档还是Beta版,可以发现下半年React团队节奏明显加快了。

v15升级到v16启用Fiber架构那天开始,React团队就在为并发更新的稳定努力了。

这一天,终于不远了......

欢迎加入人类高质量前端框架群,带飞


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK