React 18 Beta来了
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.
大家好,我卡颂。
经过React18工作组几个月工作,11月16日v18
终于从Alpha
版本更新到Beta
版本。
本文会解释:
- 这次更新带来的变化
- 对开发者的影响
- 如何安装
v18 Beta
v18
稳定版何时会来
带来的变化
经过与社区不断沟通,Beta
版将有如下三个API
变动:
useSyncExternalStore
将替代useMutableSource
用于订阅外部源,见:#86讨论
用法类似如下:
import {useSyncExternalStore} from 'react'; // 基础用法,getSnapshot返回一个缓存的值 const state = useSyncExternalStore(store.subscribe, store.getSnapshot); // 根据数据字段,使用内联的getSnapshot返回缓存的数据 const selectedField = useSyncExternalStore(store.subscribe, () => store.getSnapshot().selectedField);
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} /> </> ); );
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
团队就在为并发更新
的稳定努力了。
这一天,终于不远了......
欢迎加入人类高质量前端框架群,带飞
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK