React: 16 - 18 - 19

Links

人人都能看懂的 React : https://learnreact.design/posts/what-is-react/zh

React 周边

https://github.com/nfl/react-helmet 插入原生 head,比如 meta

React 16 -> 18(并发)

React 中的事件机制. 批量渲染,不能跨事件,onClick,addEventListener, Concurrent Mode,Sync Render

React 19 English Blog

https://react.dev/blog/2024/04/25/react-19

Tips

React 19 存在新的呢? useActionState, useFormStatus, useOptimistic, use
React 19 存在升级呢? <ThemeContext; ref clean; useDeferredValue; initialValue; 文档元数据 手动加载样式表 支持异步脚本 资源预加载 错误处理(createRoot 存在三个错误处理选项)
React 19 我好奇的? React Compiler

Keywords

  • JSX Transform

安装

{
  "dependencies": {
    "@types/react": "npm:types-react@beta",
    "@types/react-dom": "npm:types-react-dom@beta"
  },
  "overrides": {
    "@types/react": "npm:types-react@beta",
    "@types/react-dom": "npm:types-react-dom@beta"
  }
}

破坏性变更

  • Error in render 不会抛出两次了
  • 移除废弃的 API
    • ReactDOM.render was deprecated in March 2022 (v18.0.0)
    • 19 Deprecated: element.ref
    • 19 Deprecated: react-test-renderer

值得关注的

  • 支持ESM - based CDN
  <script type="module">
    import React from "https://esm.sh/react@19/?dev"
    import ReactDOMClient from "https://esm.sh/react-dom@19/client?dev"
  </script>
  • Ref cleanups required
  • useRef requires an argument
    之前会遇到以下这种情况,但是现在不会了
const ref = useRef < number > null;
// Can not assign to 'current' because it is a read-only property
ref.current = 1;
  • The JSX namespace in TypeScript (scoped jsx)
  declare module "react"

New Features

actions

useTransition ; useOptimistic; use

const [isPending, startTransition] = useTransition( );

use API

  • use hook is preferred over useContext hook, because it is more flexible.
const theme = use(ThemeContext);

ref as a prop

deprecate forwardRef

<Context /> as a provider

<ThemeContext value="dark"> {children} </ThemeContext>

Cleanup functions for refs

类似useEffect的使用

ref => {
  // ref created
  ...
  // NEW: return a cleanup function to reset
  // The ref when element is removed from DOM.
  return () => {
    // ref cleanup
  };
};

useDeferredValue

类比防抖节流函数, 只不过useDeferredValue更适合优化渲染
是一个体验优化,可以延迟渲染UI的某一个部分,也就是里面包裹的是state
官方例子: searchBar + list: 可以将 list 的 result 使用useDeferredValue包裹一下

Additional

  • If you have a lot of unsound access to xxx.
  • Some of the removed have types been moved to more relevant packages.
  • You will make an API request, and then handle the response. Then, we have to handle pending states, errors,optimistic updates, and sequential requests.
  • The main difference between useDeferredValue and unoptimized re-rendering
  • Let’s walk through an example to see when this is useful.

Magic

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容