Introduction
Introduction to Reality
What is react?
React is a JavaScript library for the user interface. It was developed and maintained by Facebook (now Meta) and opened in 2013. React was originally designed to help developers build complex user interfaces while maintaining the maintenance and scalability of codes.
React features
-
Componentization: React makes the code easier to manage and maintain by decomposing UIs into separate, reusable components. Each component focuses only on its own logic and view.
-
Declaration programming: React uses a declarative programming style, and the developer needs only to describe what UI should look like, not manual DOM. React automatically updates UIs as data changes.
-
Virtual DOM: React uses virtual DOM to optimize UI updates. When data change, React creates a new virtual DOM, then compares it with the previous virtual DOM, identifies the smallest changes and applies them to the actual DOM, thereby improving performance.
-
One-way data flows: React uses one-way data flows (also known as one-way data binding), which means that data are transmitted between components through props, making data flows clearer and more predictable.
-
Ecosystems: React has a large and active community, providing a large number of third-party banks and tools, such as React Router (for route management) and Redux (for state management), to help developers build complex applications.
Pre-knowledge
React:
- JavaScript
(es6+) - HTML
- CSS
- TypeScript (basic) Typescript
- Npm Package Manager
React Market Situation
npm statistics (excluding mirrors) 2024-9-4
- React 18.3.1 weekly download
22,538,510 - vue 3.4.31 Weekly download
4,699,312 - Angular 18.1.0 weekly download
3,216,414 - jQuery 3.7.10 Weekly download
10,210,940 288,278
Installation of environmental readiness
- node.js Download address: https://nodejs.org/en ** It is proposed to install more than 18 versions or to use nvm to manage the node version**
- vsocde editor (twirl or like other editor if installed) https://code.visualstudio.com/
- Vscode plugin installation option (
Simple React Snippets)


React Development Environmental Construction
Select a directory you like, and then run the following command:
npm init vite
- Once the execution is complete, you will enter the project name, for example
react-demo - Then you'll choose a frame and then choose
react - Then choose
TypeScript + SWCand if you don't, select js

Introduction to Contents
- public public directory
- src
- Assets static resources
- App.css Root Component Style
- App.tsx root component
- index.css global csss files
- Global tsx files
- Vite-env.d.ts Declaration File
- .eslintrc.cjs eslint profile
- .gitignoreget ignores files
- index.html Entry file index.html
- Package.json projects rely on modular files
- tsconfig.jsonts profile
- tsconfig.node.json vite-ts profile
- Vite.config.ts vite profile
FAQ:
- The public directory and the assets static resources?
Response: The resource compiled for the public catalogue will be stored in the root directory, while static resourcessets will be packed with the project and public will not be compiled.
- ** Why do you add one to the main.tsx
document.getElementById('root')!**
Response: As return document.getElementById('root') may be empty, errors will be reported at this time. It's a non-empty assertion, telling the editor that this expression is not empty.
Command description (package.json)
"dev": "vite",//启动开发模式项目
"build": "tsc && vite build", //打包构建生产包
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",//代码检查
"preview": "vite preview" //预览模式
Eslint command details.
eslint .:对当前目录(以及子目录)中的文件运行 ESLint。
--ext ts,tsx:指定要检查的文件扩展名为 .ts 和 .tsx,即 TypeScript 和 TypeScript React 文件。
--report-unused-disable-directives:报告未使用的 eslint-disable 指令。这可以帮助你清理不再需要的 ESLint 禁用指令。
--max-warnings 0:将警告数量限制为 0。如果有任何警告,ESLint 将返回非零退出代码,这通常用于在 CI/CD 环境中确保代码库没有任何警告。
Introduction to tsx syntax
FAQ
What's the difference between tsx and jsx?
There is little difference but the addition of a type to the jsx syntax.
What's jsx?
A: jsx is a syntax extension of js to allow html code to be written in js.
Example: Who's Misaki? Never heard of it.
Syntax:
- Use tsx binding variable
{value}
Class to bind
function App() {
const num: number = 333
const fn = () => "test"
return (
<>
{"11" /** 字符串用法 */}
{num /** 变量用法 */}
{fn() /** 函数用法 */}
{new Date().getTime() /** 日期用法 */}
</>
)
}
//绑定class(className) id 属性等等 都是一样的
function App() {
const value: string = "A"
return (
<>
<div data-index={value} className={value} id={value}>
{value}
</div>
</>
)
}
//绑定多个class(className)
function App() {
const a: string = "A"
return (
<>
<div className={`${a} class2`}>{value}</div>
</>
)
}
//绑定样式style
function App() {
const styles = { color: "red" }
return (
<>
<div style={styles}>test</div>
</>
)
}
- Use tsx to bind the event
on[Click]{fn}.
function App() {
const value: string = "小满"
const clickTap = (params: string) => console.log(params)
return (
<>
<div onClick={() => clickTap(value)}>{value}</div>
</>
)
}
- How tsx uses pane
Normal generic grammar conflicts with tsx syntax, and he understands it as an element, followed by a solution, i.e. Yeah.
function App() {
const value: string = "小满"
const clickTap = <T,>(params: T) => console.log(params)
return (
<>
<div onClick={() => clickTap(value)}>{value}</div>
</>
)
}
- tsx how to render html Snippets (dangerously SetInnerHTML)
The value of dangerously SetInnerHTML is an object that contains an attribute named html and values the HTML string you want to insert
function App() {
const value: string = '<section style="color:red">小满</section>'
return (
<>
<div dangerouslySetInnerHTML={{ __html: value }}></div>
</>
)
}
- How tsx cross-dom elements
Use Map to return html tags
function App() {
const arr: string[] = ["小满", "中满", "大满"]
return (
<>
{arr.map((item) => {
return <div>{item}</div>
})}
</>
)
}
- tsx how to write conditional statements
Use a three-dollar expression.
function App() {
const flag: boolean = true
return <>{flag ? <div>真的</div> : <div>假的</div>}</>
}
- Tsx Attention
** {} Plugin statement does not allow switch if Variable declaration or directly Object Body**
Here's the correct comparison of the wrong use.
//错误用法
function App() {
const obj = { name: "小满" }
return <>{obj}</>
}
//正确用法
function App() {
const obj = { name: "小满" }
return (
<>
{obj.name}
{JSON.stringify(obj)}
</>
)
}
//错误用法
function App() {
const flag:boolean = true
return (
<>
{
if(flag){
<p>1</p>
}else{
<p>2</p>
}
}
</>
)
}
//正确用法
function App() {
const flag:boolean = true
return (
<>
{
flag ? <div>1</div> : <div>2</div>
}
</>
)
}
Tools
Babel
What's Babel?
Babel is a JavaScript compiler that provides the JavaScript compilation process that allows the source code to be converted to the target code.
AST -> Transform -> Generate
Network https://babeljs.io/
View AST https://astexplorer.net/
All Babel's bags https://babeljs.io/docs/babel-traverse
Core functions
- Syntax: Convert new JavaScript syntax to old syntax
- Polyfil: New functionality available in old browser by introducing additional codes
- JSX: Conversion of JSX syntax to normal JavaScript syntax
- Plugin: Provide a custom function for Abel
Cases
Syntax: Conversion of the new JavaScript syntax to the old syntax
npm install --save-dev @babel/core @babel/cli @babel/preset-env
test.js
//语法
const a = (params = 2) => 1 + params
const b = [1, 2, 3]
const c = [...b, 4, 5]
class Babel {}
new Babel()
//API
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter((x) => x % 2 === 0)
const y = Object.assign({}, { name: 1 })
index.js Core Conversion Code
//记得设置package.json的type为module
import Babel from "@babel/core"
import presetEnv from "@babel/preset-env"
import fs from "node:fs"
const file = fs.readFileSync("./test.js", "utf8")
const result = Babel.transform(file, {
presets: [presetEnv],
})
console.log(result.code)
Compiled Code
"use strict"
function _typeof(o) {
"@babel/helpers - typeof"
return (
(_typeof =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function (o) {
return typeof o
}
: function (o) {
return o &&
"function" == typeof Symbol &&
o.constructor === Symbol &&
o !== Symbol.prototype
? "symbol"
: typeof o
}),
_typeof(o)
)
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t]
;((o.enumerable = o.enumerable || !1),
(o.configurable = !0),
"value" in o && (o.writable = !0),
Object.defineProperty(e, _toPropertyKey(o.key), o))
}
}
function _createClass(e, r, t) {
return (
r && _defineProperties(e.prototype, r),
t && _defineProperties(e, t),
Object.defineProperty(e, "prototype", { writable: !1 }),
e
)
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string")
return "symbol" == _typeof(i) ? i : i + ""
}
function _toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t
var e = t[Symbol.toPrimitive]
if (void 0 !== e) {
var i = e.call(t, r || "default")
if ("object" != _typeof(i)) return i
throw new TypeError("@@toPrimitive must return a primitive value.")
}
return ("string" === r ? String : Number)(t)
}
function _classCallCheck(a, n) {
if (!(a instanceof n))
throw new TypeError("Cannot call a class as a function")
}
var a = function a() {
var params =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2
return 1 + params
}
var b = [1, 2, 3]
var c = [].concat(b, [4, 5])
var Babel = /*#__PURE__*/ _createClass(function Babel() {
_classCallCheck(this, Babel)
})
new Babel()
How to support new features, such as:
npm i core-js -D
index.js Enhanced compile
import Babel from "@babel/core"
import presetEnv from "@babel/preset-env"
import fs from "node:fs"
const file = fs.readFileSync("./test.js", "utf8")
const result = Babel.transform(file, {
//usage 会根据配置的浏览器兼容,以及你代码中用到的 API 来进行 polyfill,实现了按需添加
//corejs 3 是corejs的版本
presets: [[presetEnv, { useBuiltIns: "usage", corejs: 3 }]],
})
console.log(result.code)
Code after conversion
"use strict"
require("core-js/modules/es.symbol.js")
require("core-js/modules/es.symbol.description.js")
require("core-js/modules/es.symbol.iterator.js")
require("core-js/modules/es.symbol.to-primitive.js")
require("core-js/modules/es.array.iterator.js")
require("core-js/modules/es.date.to-primitive.js")
require("core-js/modules/es.number.constructor.js")
require("core-js/modules/es.object.define-property.js")
require("core-js/modules/es.string.iterator.js")
require("core-js/modules/web.dom-collections.iterator.js")
function _typeof(o) {
"@babel/helpers - typeof"
return (
(_typeof =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function (o) {
return typeof o
}
: function (o) {
return o &&
"function" == typeof Symbol &&
o.constructor === Symbol &&
o !== Symbol.prototype
? "symbol"
: typeof o
}),
_typeof(o)
)
}
require("core-js/modules/es.array.concat.js")
require("core-js/modules/es.array.filter.js")
require("core-js/modules/es.object.assign.js")
require("core-js/modules/es.object.to-string.js")
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t]
;((o.enumerable = o.enumerable || !1),
(o.configurable = !0),
"value" in o && (o.writable = !0),
Object.defineProperty(e, _toPropertyKey(o.key), o))
}
}
function _createClass(e, r, t) {
return (
r && _defineProperties(e.prototype, r),
t && _defineProperties(e, t),
Object.defineProperty(e, "prototype", { writable: !1 }),
e
)
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string")
return "symbol" == _typeof(i) ? i : i + ""
}
function _toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t
var e = t[Symbol.toPrimitive]
if (void 0 !== e) {
var i = e.call(t, r || "default")
if ("object" != _typeof(i)) return i
throw new TypeError("@@toPrimitive must return a primitive value.")
}
return ("string" === r ? String : Number)(t)
}
function _classCallCheck(a, n) {
if (!(a instanceof n))
throw new TypeError("Cannot call a class as a function")
}
//语法
var a = function a() {
var params =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2
return 1 + params
}
var b = [1, 2, 3]
var c = [].concat(b, [4, 5])
var Babel = /*#__PURE__*/ _createClass(function Babel() {
_classCallCheck(this, Babel)
})
new Babel()
//API
var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(function (x) {
return x % 2 === 0
})
var y = Object.assign(
{},
{
name: 1,
}
)
2.jsx code conversion
Test Example test.test.jsx
import react from "react"
import { createRoot } from "react-dom/client"
const App = () => {
return <div>小满是谁?????</div>
}
createRoot(document.getElementById("root")).render(<App />)
Write code with only one preset
npm install @babel/preset-react -D
import Babel from "@babel/core"
import presetEnv from "@babel/preset-env"
import fs from "node:fs"
import react from "@babel/preset-react"
const file = fs.readFileSync("./test.jsx", "utf8")
const result = Babel.transform(file, {
presets: [[presetEnv, { useBuiltIns: "usage", corejs: 3 }], react],
})
console.log(result.code)
Result of conversion
It's actually called
React.createElementto create elements.
"use strict"
var _react = _interopRequireDefault(require("react"))
var _client = require("react-dom/client")
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e }
}
var App = function App() {
return /*#__PURE__*/ React.createElement(
"div",
null,
"\u5C0F\u6EE1\u662F\u8C01\uFF1F\uFF1F\uFF1F\uFF1F\uFF1F"
)
}
;(0, _client.createRoot)(document.getElementById("root")).render(
/*#__PURE__*/ React.createElement(App, null)
)
Preparation of the Babel plugin
import Babel from "@babel/core"
import fs from "node:fs"
const file = fs.readFileSync("./test.js", "utf8")
//babel会注入一个types对象里面包含了各种ast节点的方法
const transformFunction = ({ types: t }) => {
return {
name: "babel-transform-function",
//visitor 是一个对象,它包含了一组方法,这些方法对应于 AST 中的不同节点类型。每当 Babel 遇到某种类型的节点时,都会调用 visitor 中对应的方法。
visitor: {
//匹配 箭头函数 当然也可以匹配别的东西 这儿只是案例
ArrowFunctionExpression(path) {
const node = path.node
const arrowFunction = t.functionExpression(
null, //node.id 是一个 Identifier 节点,表示函数名
node.params, //node.params 是一个数组,表示函数的参数
// BlockStatement 是 JavaScript 抽象语法树(AST)中的一种节点类型,表示一个由大括号 {} 包围的语句块。它是函数体、循环体、条件分支(如 if 语句)等代码块的基础结构
t.blockStatement([t.returnStatement(node.body)]), //node.body 是函数的主体,通常是一个 BlockStatement 节点
node.async //node.async 是一个布尔值,表示函数是否是异步的 (async 函数)
)
path.replaceWith(arrowFunction) //替换当前节点
},
},
}
}
const result = Babel.transform(file, {
plugins: [transformFunction],
})
console.log(result.code)
Results after conversion
//语法
const a = function (params = 2) {
return 1 + params
}
const b = [1, 2, 3]
const c = [...b, 4, 5]
class Babel {}
new Babel()
//API
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(function (x) {
return x % 2 === 0
})
const y = Object.assign(
{},
{
name: 1,
}
)
swc
What's swc?
SWC can be used both for compilation and for packing. For compilation, it uses modern JavaScript to access JavaScript / TypeScript files and to export valid codes supported by all mainstream browsers.
SWC is 20 times faster on a single line than Babel and 70 times faster on the four cores.
Simply put, swc has the same function as babel, but it's faster than babel.
Why is FAQ fast?
-
Compile Type Rust is a compiler language that converts the code into a machine code (the bottom CPU command). This machine code is very efficient in its implementation and hardly requires additional costs.
-
Explanation JavaScript is an explanatory language that usually operates through an interpreter in a browser or Node.js environment. Although modern JavaScript engines (e.g. V8 engines) use JIT (immediate compilation) to improve performance, the explanatory language essentially requires additional running costs.
Compiler principle for v8 https://juejin.cn/post/7291135064843304994#heading-0
Swc https://swc.rs/
Core functions
- JavaScript/TypeScript conversion can convert modern JavaScript (ES6+) and TypeScript codes to codes compatible with the old JavaScript environment. This includes syntax conversions (e.g. arrow functions, deconstructive values, etc.) and some processing of polyfill
- SWC provides a basic packing function that binds multiple modules into a single file
- SWC supports code compression and optimization, similar to Terser. It compresses the JavaScript code, removes unnecessary blanks, comments, and optimizes the code to reduce file size and increase loading speed
- SWC Original Support TypeScript, which can be compiled into JavaScript
- SWC supports React and JSX syntax by converting JSX to the standard JavaScript code. It also supports some modern React features
Cases
Syntax: Conversion of the new JavaScript syntax to the old syntax
Before conversion
//语法
const a = (params = 2) => 1 + params
const b = [1, 2, 3]
const c = [...b, 4, 5]
class Babel {}
new Babel()
//API
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter((x) => x % 2 === 0)
const y = Object.assign({}, { name: 1 })
swc convert code
import swc from "@swc/core"
const result = swc.transformFileSync("./test.js", {
jsc: {
target: "es5", //代码转换es5
parser: {
syntax: "ecmascript",
},
},
})
console.log(result.code)
Results after conversion
//语法
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]
return arr2
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array(arr)
}
function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function")
}
}
function _iterable_to_array(iter) {
if (
(typeof Symbol !== "undefined" && iter[Symbol.iterator] != null) ||
iter["@@iterator"] != null
)
return Array.from(iter)
}
function _non_iterable_spread() {
throw new TypeError(
"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
)
}
function _to_consumable_array(arr) {
return (
_array_without_holes(arr) ||
_iterable_to_array(arr) ||
_unsupported_iterable_to_array(arr) ||
_non_iterable_spread()
)
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return
if (typeof o === "string") return _array_like_to_array(o, minLen)
var n = Object.prototype.toString.call(o).slice(8, -1)
if (n === "Object" && o.constructor) n = o.constructor.name
if (n === "Map" || n === "Set") return Array.from(n)
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
return _array_like_to_array(o, minLen)
}
var a = function () {
var params =
arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 2
return 1 + params
}
var b = [1, 2, 3]
var c = _to_consumable_array(b).concat([4, 5])
var Babel = function Babel() {
"use strict"
_class_call_check(this, Babel)
}
new Babel()
//API
var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(function (x) {
return x % 2 === 0
})
var y = Object.assign(
{},
{
name: 1,
}
)
When swc converts
When Babel converts
2. swc convert react jsx syntax
test.jsx
import react from "react"
import { createRoot } from "react-dom/client"
const App = () => {
return <div>小满是谁?????</div>
}
createRoot(document.getElementById("root")).render(<App />)
Convert Code
import swc from "@swc/core"
console.time()
const result = swc.transformFileSync("./test.jsx", {
jsc: {
target: "es5", //代码转换es5
parser: {
syntax: "ecmascript",
jsx: true,
},
transform: {
react: {
runtime: "automatic",
},
},
},
})
console.log(result.code)
console.timeEnd()
Result
import { jsx as _jsx } from "react/jsx-runtime"
import react from "react"
import { createRoot } from "react-dom/client"
var App = function () {
return /*#__PURE__*/ _jsx("div", {
children: "小满是谁?????",
})
}
createRoot(document.getElementById("root")).render(/*#__PURE__*/ _jsx(App, {}))
When swc converts
When Abel converts: 80.613 ms
3. Swc simple packing
As of 2024-9-4, the current function is chicken ribs.
For now, swc packs can only support cjs in the future, and esm in the future.
Create Profile spack.config.js
Write the following code to execute npx spack pack
const { config } = require("@swc/core/spack")
const path = require("path")
module.exports = config({
entry: {
web: path.join(__dirname, "./test.js"), //入口
},
output: {
path: path.join(__dirname, "./dist"), //出口
name: "test.js",
},
})
Rationale
Virtual Dom
This is the fact that a DOM structure is described with JavaScript objects. The virtual DOM is not a real DOM that directly handles the browser, but is first updated in a virtual DOM and then efficiently synchronizes changes to the real DOM.
Strengths
-
Performance optimization: Direct operation of real DOM is expensive, especially when it involves a large number of nodes. Virtual DOM, by reducing unnecessary DOM operations, is largely reflected in the reuse of diff algorithms, which does not actually improve much.
-
Cross-platform: Virtual DOM is a non-platform concept that can map different rendering targets, such as the DOM of the browser or the original UI of the mobile end
(React Native).
Achieving a simple virtual Dom
const App = () => {
return (
<div id="2">
<span>小满zs</span>
</div>
)
}
It's going to be converted from a baby or a swc.
const App = () => {
return React.createElement(
"div",
{ id: 2 },
React.createElement("span", null, "小满zs")
)
}
Then we'll make it happen.
React.createElement
-
To generate a virtual DOM tree, return an object that contains type (element type) and props (relations and sub-elements). Children may be a text or other virtual DOM object. React.createTextElement:
-
To process text nodes, encapsulate a string into a virtual DOM object. React.render:
-
Converts virtual DOM into actual DOM elements. Renders all sub-elements in a reverse way. Finally insert the generated DOM node into the specified container Medium
const React = {
createElement(type, props = {}, ...children) {
return {
type,
props: {
...props,
children: children.map(
(child) =>
typeof child === "object"
? child // 如果子元素是对象(嵌套元素),返回对象
: this.createTextElement(child) // 否则将字符串转换为文本元素
),
},
}
},
createTextElement(text) {
// 文本是没有props children什么的 这样做只是为了结构统一方便遍历
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: [],
},
}
},
}
React Fiber
Fiber is a new coordinating engine introduced by React 16 to address and optimize React's performance in complex UI rendering
React source resolve English version https://pomb.us/build-your-own-react/
Unused Fiber version https://claudiopro.github.io/react-fiber-vs-stack-demo/stack.html
Fiber version https://claudiopro.github.io/react-fiber-vs-stack-demo/fiber.html used
Fiber's role
In order to address the Carton phenomenon of React15 when large components are updated, the React team developed the Fiber structure and published it in React16, recasting the uninterruptable upgrade of the synchronized recursion into an interruptable one-step open update
It achieved four specific goals
-
Interrupable rendering: Fiber allows large rendering tasks to be split into several small units (unit of Work), allowing React to perform these small tasks during free time. When the browser needs to handle higher-priority tasks (e.g. user input, animation), you can suspend rendering, process these tasks and then resume the unfinished rendering.
-
Priority movement: Under the Fiber structure, React can determine which parts are updated according to the priorities of the different tasks. React gives priority to updating the sensory parts of the user (e.g. animation, user input), while low-priority tasks (e.g. updating the interface after data loading) can be delayed.
-
Two Cache Trees (Fiber Tree): Two Fiber Trees - Current fiber tree (Fiber tree currently being rendered) and work in process fiber tree (Fiber tree being processed). React uses these two trees to preserve the state before and after the renewal, which will allow for more efficient comparison and updating.
-
Job Slices: During the free time of the browser (using the view IdleCallback idea), React can break down the rendering task into small pieces, gradually complete the construction of the Fiber tree and avoid any disruption caused by the completion of all the rendering tasks at once.
Double Cache
Two trees inside the react maintain two states: one fiber tree and one work in progress fiber tree
- Fiber tree: is currently being rendered
- Work in progress Fiber tree: represents the new Fiber tree generated during the update, which is the next UI status to be rendered
For example:
When we draw animations with canvas, we use ctx.clarRect to clear the image of the previous frame before drawing it, and if the current frame count is larger, the white screen will appear if there is a long gap between the removal of the previous frame and the drawing of the current frame.
In order to solve this problem, we can draw the current frame animation in our memory and then replace the previous frame directly with the current frame, without flashing from the white screen to the image because the time between the two frames is saved.
In-depth understanding of mission slices
You have to understand the slice first.
What does a browser do?
- Deals with incident click... incident
- Process timer echoes
- Start Frame
- Execute requestAnimation Frame
- Computer Page Layout Calculating Merge to Main Line Cheng
- Draw
- If there's still time available to execute requestIdleCallback
For example, to update 10,000 doms
We can update it in three small missions.
And insert requestIdleCallback for each task as requestIdleCallback

Diff algorithm
There are four AB, C, D nodes.
Well, first of all, react will turn this node into a chain structure.
root
|
child
↓
A -> B -> C -> D
And then we updated the node.
Then diff algorithm.
- He'll find a reusable node from the map.
- If this structure doesn't appear at
Ethen it's new to create a new Fiber structure. - If the old node exists, then the new node is deleted.

Code completes vDom Fiber Diff Version
//vdom
const React = {
createElement(type, props = {}, ...children) {
return {
type,
props: {
...props,
children: children.map((child) =>
typeof child === "object" ? child : React.createTextElement(child)
),
},
}
},
createTextElement(text) {
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: [],
},
}
},
}
// const vdom = React.createElement('div', { id: 1 }, React.createElement('span', null, '小满zs'));
// console.log(vdom)
//Fiber 是 React 16 引入的一种新的协调引擎
let nextUnitOfWork = null // 下一个工作单元
let currentRoot = null // 当前 Fiber 树的根
let wipRoot = null // 正在工作的 Fiber 树
let deletions = null // 存储需要删除的 Fiber
// Fiber 渲染入口
function render(element, container) {
//wipRoot 表示“正在进行的工作根”,它是 Fiber 架构中渲染任务的起点
wipRoot = {
dom: container, //渲染目标的 DOM 容器
props: {
children: [element], //要渲染的元素(例如 React 元素)
},
alternate: currentRoot,
//alternate 是 React Fiber 树中的一个关键概念,用于双缓冲机制(双缓冲 Fiber Tree)。currentRoot 是之前已经渲染过的 Fiber 树的根,wipRoot 是新一轮更新的根 Fiber 节点。
//它们通过 alternate 属性相互关联
//旧的fiber树
}
nextUnitOfWork = wipRoot
//nextUnitOfWork 是下一个要执行的工作单元(即 Fiber 节点)。在这里,将其设置为 wipRoot,表示渲染工作从根节点开始
deletions = []
//专门用于存放在更新过程中需要删除的节点。在 Fiber 更新机制中,如果某些节点不再需要,就会将它们放入 deletions,
//最后在 commitRoot 阶段将它们从 DOM 中删除
}
// 创建 Fiber 节点
function createFiber(element, parent) {
return {
type: element.type,
props: element.props,
parent,
dom: null, // 关联的 DOM 节点
child: null, // 子节点
sibling: null, // 兄弟节点
alternate: null, // 对应的前一次 Fiber 节点
effectTag: null, // 'PLACEMENT', 'UPDATE', 'DELETION'
}
}
// 创建 DOM 节点
function createDom(fiber) {
const dom =
fiber.type === "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(fiber.type)
updateDom(dom, {}, fiber.props)
return dom
}
// 更新 DOM 节点属性
function updateDom(dom, prevProps, nextProps) {
// 移除旧属性
Object.keys(prevProps)
.filter((name) => name !== "children")
.forEach((name) => {
dom[name] = ""
})
// 添加新属性
Object.keys(nextProps)
.filter((name) => name !== "children")
.filter((name) => prevProps[name] !== nextProps[name])
.forEach((name) => {
dom[name] = nextProps[name]
})
}
// Fiber 调度器
// 实现将耗时任务拆分成多个小的工作单元
function workLoop(deadline) {
//deadline 表示浏览器空闲时间
let shouldYield = false
//是一个标志,用来指示是否需要让出控制权给浏览器。如果时间快用完了,则设为 true,以便及时暂停任务,避免阻塞主线程
while (nextUnitOfWork && !shouldYield) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork)
//performUnitOfWork 是一个函数,它处理当前的工作单元,并返回下一个要执行的工作单元。每次循环会更新 nextUnitOfWork 为下一个工作单元
shouldYield = deadline.timeRemaining() < 1
//使用 deadline.timeRemaining() 来检查剩余的空闲时间。如果时间少于 1 毫秒,就设置 shouldYield 为 true,表示没有空闲时间了,就让出控制权
}
if (!nextUnitOfWork && wipRoot) {
//当没有下一个工作单元时(nextUnitOfWork 为 null),并且有一个待提交的“工作根”(wipRoot),就会调用 commitRoot() 将最终的结果应用到 DOM 中
commitRoot()
}
requestIdleCallback(workLoop)
//使用 requestIdleCallback 来安排下一个空闲时间段继续执行 workLoop,让任务在浏览器空闲时继续进行
}
//requestIdleCallback 浏览器绘制一帧16ms 空闲的时间去执行的函数 浏览器自动执行
//浏览器一帧做些什么
//1.处理时间的回调click...事件
//2.处理计时器的回调
//3.开始帧
//4.执行requestAnimationFrame 动画的回调
//5.计算机页面布局计算 合并到主线程
//6.绘制
//7.如果此时还有空闲时间,执行requestIdleCallback
requestIdleCallback(workLoop)
// 执行一个工作单元
function performUnitOfWork(fiber) {
// 如果没有 DOM 节点,为当前 Fiber 创建 DOM 节点
if (!fiber.dom) {
fiber.dom = createDom(fiber)
}
//确保每个 Fiber 节点都在内存中有一个对应的 DOM 节点准备好,以便后续在提交阶段更新到实际的 DOM 树中
// 创建子节点的 Fiber
// const vdom = React.createElement('div', { id: 1 }, React.createElement('span', null, '小满zs'));
// 子节点在children中
const elements = fiber.props.children
reconcileChildren(fiber, elements)
// 返回下一个工作单元(child, sibling, or parent)
if (fiber.child) {
return fiber.child
}
let nextFiber = fiber
while (nextFiber) {
if (nextFiber.sibling) {
return nextFiber.sibling
}
nextFiber = nextFiber.parent
}
return null
}
// Diff 算法: 将子节点与之前的 Fiber 树进行比较
function reconcileChildren(wipFiber, elements) {
let index = 0 //
let oldFiber = wipFiber.alternate && wipFiber.alternate.child // 旧的 Fiber 树
let prevSibling = null
while (index < elements.length || oldFiber != null) {
const element = elements[index]
let newFiber = null
// 比较旧 Fiber 和新元素
const sameType = oldFiber && element && element.type === oldFiber.type
//如果是同类型的节点,复用
if (sameType) {
newFiber = {
type: oldFiber.type,
props: element.props,
dom: oldFiber.dom,
parent: wipFiber,
alternate: oldFiber,
effectTag: "UPDATE",
}
}
//如果新节点存在,但类型不同,新增fiber节点
if (element && !sameType) {
newFiber = createFiber(element, wipFiber)
newFiber.effectTag = "PLACEMENT"
}
//如果旧节点存在,但新节点不存在,删除旧节点
if (oldFiber && !sameType) {
oldFiber.effectTag = "DELETION"
deletions.push(oldFiber)
}
//移动旧fiber指针到下一个兄弟节点
if (oldFiber) {
oldFiber = oldFiber.sibling
}
// 将新fiber节点插入到DOM树中
if (index === 0) {
//将第一个子节点设置为父节点的子节点
wipFiber.child = newFiber
} else if (element) {
//将后续子节点作为前一个兄弟节点的兄弟
prevSibling.sibling = newFiber
}
//更新兄弟节点
prevSibling = newFiber
index++
}
}
// 提交更新到 DOM
function commitRoot() {
deletions.forEach(commitWork) // 删除需要删除的 Fiber 节点
commitWork(wipRoot.child)
currentRoot = wipRoot
wipRoot = null
}
// 提交单个 Fiber 节点
function commitWork(fiber) {
if (!fiber) {
return
}
const domParent = fiber.parent.dom
if (fiber.effectTag === "PLACEMENT" && fiber.dom != null) {
domParent.appendChild(fiber.dom)
} else if (fiber.effectTag === "UPDATE" && fiber.dom != null) {
updateDom(fiber.dom, fiber.alternate.props, fiber.props)
} else if (fiber.effectTag === "DELETION") {
domParent.removeChild(fiber.dom)
}
commitWork(fiber.child)
commitWork(fiber.sibling)
}
//测试
// render(React.createElement('h1', null, 'hello world'), document.getElementById('root'));
// 测试用例diff
render(
React.createElement(
"div",
{ id: 1 },
React.createElement("span", null, "hello 11")
),
document.getElementById("root")
)
render(
React.createElement(
"div",
{ id: 1 },
React.createElement("span", null, "hello 22")
),
document.getElementById("root")
)
requestidlecallback
It provides a mechanism that allows developers to run low-priority tasks when the browser is idle without affecting the performance of key tasks and animations.
execution phase
- Deals with incident click... incident
- Process timer echoes
- Start Frame
- Execute requestAnimation Frame
- Computer Page Layout Calculating Merge to Main Line Cheng
- Draw
- If there's still time available to execute requestIdleCallback
Basic use of requessidlecallback
Accepts a callback function callback and injects parameters deadline in the callback function
Deadline has two values:
-
deadline.timeRemaining()returns free time (ms) -
deadline.didTimeoutWhether returns are enforced because they are time-exceeded (bull value)
options:
{ timeout: 1000 }Specifies the maximum waiting time for callback (in milliseconds). If there is no free time at the specified timeout, callback will be enforced to avoid indefinite postponement
This case simulates the rendering of 1000 dom elements when the browser is idle, which is very fluid.
const total = 1000 // 定义需要生成的函数数量,即1000个任务
const arr = [] // 存储任务函数的数组
// 生成1000个函数并将其添加到数组中
function generateArr() {
for (let i = 0; i < total; i++) {
// 每个函数的作用是将一个 <div> 元素插入到页面的 body 中
arr.push(function () {
document.body.innerHTML += `<div>${i + 1}</div>` // 将当前索引 + 1 作为内容
})
}
}
generateArr() // 调用函数生成任务数组
// 用于调度和执行任务的函数
function workLoop(deadline) {
// 检查当前空闲时间是否大于1毫秒,并且任务数组中还有任务未执行
if (deadline.timeRemaining() > 1 && arr.length > 0) {
const fn = arr.shift() // 从任务数组中取出第一个函数
fn() // 执行该函数,即插入对应的 <div> 元素到页面中
}
// 再次使用 requestIdleCallback 调度下一个空闲时间执行任务
requestIdleCallback(workLoop)
}
// 开始调度任务,在浏览器空闲时执行 workLoop
requestIdleCallback(workLoop, { timeout: 1000 })
The interview officer might ask questions.
Why does React not use the original request IdleCallback?
-
Poor compatibilitySafariis not supported (see figure below) https://caniuse.com/?search=requestIdleCallback -
Control precisionReact to organize the rendering more precisely on the basis of information on the priority of components, the urgency of updates, etc. -
Timing of implementationrequestIdleCallback (callback) executes 50 ms (W3C) or 20 times 20 times within a second and longer. -
DifferenceEach browser achieves the API in a different way, resulting in different timings and slowness

What's the alternative to reqestIdleCallback?
MessageChannel
The reason for choosing MessageChannel is that it is an ambitious task to move from one step to another, since the macro task will be performed in the next event cycle and will not block the current page update. MessageChannel is an ambitious task.
The common setTimeout is not selected because MessageChannel can be executed faster and triggers in 0-1 ms, like setTimeout needs 4-5 ms even if setting timeout is 0. At the same time, Message Channel can do more.

MDN https://developer.mozilla.org/zh-CN/docs/Web/API/setTimeout
If the browser does not support MessageChannel, it must be downgraded to setTimeout.
Message Channel Basic
MessageChanne was designed to facilitate our communication between different contexts, such as web Worker, iframe
It provides two ports (port1 and port2) through which information can be transmitted in two directions between separate lines
// 创建 MessageChannel
const channel = new MessageChannel()
const port1 = channel.port1
const port2 = channel.port2
// 设置 port1 的消息处理函数
port1.onmessage = (event) => {
console.log("Received by port1:", event.data)
port1.postMessage("Reply from port1") // 向 port2 发送回复消息
}
// 设置 port2 的消息处理函数
port2.onmessage = (event) => {
console.log("Received by port2:", event.data)
}
// 通过 port2 发送消息给 port1
port2.postMessage("Message from port2")
Realization of react simple scheduler
React Scheduler assigns priority to each task
- Immediate Capacity: Priority for immediate implementation, highest level
- AserBlocingPriority: user blocking level priority
- NormalPriority: Normal Priority
- LowPriority: Low Priority
- IdlePriority: lowest priority
At the same time, each task is set to expire, the shorter the time, the higher the priority.
Declaration of the taskQueue group, store information for each task, including priority, expiry time, callback function
Declares isPerformingWork as a boolean value, indicating whether the task is currently being performed
Declare port as Message Channel for sending and receiving messages
Then add the task to the queue, and when you add it, you also have to sort it according to priority, and then call the work Loop on the task
const ImmediatePriority = 1 // 立即执行的优先级, 级别最高 [点击事件,输入框,]
const UserBlockingPriority = 2 // 用户阻塞级别的优先级, [滚动,拖拽这些]
const NormalPriority = 3 // 正常的优先级 [redner 列表 动画 网络请求]
const LowPriority = 4 // 低优先级 [分析统计]
const IdlePriority = 5 // 最低阶的优先级, 可以被闲置的那种 [console.log]
// 获取当前时间
function getCurrentTime() {
return performance.now()
}
class SimpleScheduler {
constructor() {
this.taskQueue = [] // 任务队列
this.isPerformingWork = false // 当前是否在执行任务
// 使用 MessageChannel 处理任务调度
const channel = new MessageChannel()
this.port = channel.port2
channel.port1.onmessage = this.performWorkUntilDeadline.bind(this)
}
// 调度任务
scheduleCallback(priorityLevel, callback) {
const curTime = getCurrentTime()
let timeout
// 根据优先级设置超时时间
switch (priorityLevel) {
case ImmediatePriority:
timeout = -1
break
case UserBlockingPriority:
timeout = 250
break
case LowPriority:
timeout = 10000
break
case IdlePriority:
timeout = 1073741823
break
case NormalPriority:
default:
timeout = 5000
break
}
const task = {
callback,
priorityLevel,
expirationTime: curTime + timeout, // 直接根据当前时间加上超时时间
}
this.push(this.taskQueue, task) // 将任务加入队列
this.schedulePerformWorkUntilDeadline()
}
// 通过 MessageChannel 调度执行任务
schedulePerformWorkUntilDeadline() {
if (!this.isPerformingWork) {
this.isPerformingWork = true
this.port.postMessage(null) // 触发 MessageChannel 调度
}
}
// 执行任务
performWorkUntilDeadline() {
this.isPerformingWork = true
this.workLoop()
this.isPerformingWork = false
}
// 任务循环
workLoop() {
let curTask = this.peek(this.taskQueue)
while (curTask) {
const callback = curTask.callback
if (typeof callback === "function") {
callback() // 执行任务
}
this.pop(this.taskQueue) // 移除已完成任务
curTask = this.peek(this.taskQueue) // 获取下一个任务
}
}
// 获取队列中的任务
peek(queue) {
return queue[0] || null
}
// 向队列中添加任务
push(queue, task) {
queue.push(task)
queue.sort((a, b) => a.expirationTime - b.expirationTime) // 根据优先级排序,优先级高的在前 从小到大
}
// 从队列中移除任务
pop(queue) {
return queue.shift()
}
}
// 测试
const scheduler = new SimpleScheduler()
scheduler.scheduleCallback(LowPriority, () => {
console.log("Task 1: Low Priority")
})
scheduler.scheduleCallback(ImmediatePriority, () => {
console.log("Task 2: Immediate Priority")
})
scheduler.scheduleCallback(IdlePriority, () => {
console.log("Task 3: Idle Priority")
})
scheduler.scheduleCallback(UserBlockingPriority, () => {
console.log("Task 4: User Blocking Priority")
})
scheduler.scheduleCallback(NormalPriority, () => {
console.log("Task 5: Normal Priority")
})
The order of execution is 2 4 5 1 3
Component
Component
What are the components?
At this point, App is a single body, and when we really do the project, we need to break it down into manageable, descriptive components. React there's no rigidity about what's and what's not. It's entirely up to you!
React Outstanding Project https://win11.blueedge.me/
Get this chapter code https://github.com/message163/react-course.git branch card-component
Define first component
If you don't have experience with component development, then remember my guidelines:
- If it's a piece in the program, then it's a component.
- If it happens regularly in the program, it's part of the program.
Use the generic UI element as a component so that you can change only one and change all places where the component is used
Preparation of the Card Component
For example, in a project, we often use a card component to create a card component.
We'll create a new folder components
Directory structure:
- components
- Card
- index.tsx
- index.css
index.css
.card {
background: white;
border-radius: 5px;
border: 1px solid #ccc;
max-width: 500px;
box-shadow: 3px 3px 3px #ccc;
header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #ccc;
padding: 10px;
div:last-child {
color: #1677ff;
}
}
main {
min-height: 200px;
border-bottom: 1px solid #ccc;
padding: 10px;
}
footer {
display: flex;
justify-content: flex-end;
align-items: center;
padding: 10px;
button {
margin-left: 10px;
padding: 3px 10px;
}
}
}
index.tsx
import "./index.css"
export default function Card() {
return (
<div className="card">
<header>
<div>标题</div>
<div>副标题</div>
</header>
<main>内容区域</main>
<footer>
<button>确认</button>
<button>取消</button>
</footer>
</div>
)
}
App.tsx Introduction Card Component
This is called a local component, which page you need to use and which page you can introduce!
import Card from "./components/Card"
function App() {
return (
<>
<Card></Card>
<Card></Card>
<Card></Card>
</>
)
}

Global Component
Directory structure:
- components
- Message
- index.tsx
- index.css
Message/index.css
.message {
width: 160px;
height: 30px;
position: fixed;
top: 10px;
left: 50%;
margin-left: -80px;
background: #fff;
border: 1px solid #ccc;
text-align: center;
line-height: 30px;
border-radius: 5px;
}
Message/index.tsx
Creates a queue queue that can be saved in arrays by clicking multiple times, and adds up to each height, so that the elements do not overlap, but are moved, so a queue queue is required and deleted in order.
import ReactDom from "react-dom/client"
import "./index.css"
const Message = () => {
return <div>提示组件</div>
}
interface Itesm {
messageContainer: HTMLDivElement
root: ReactDom.Root
}
const queue: Itesm[] = []
window.onShow = () => {
const messageContainer = document.createElement("div")
messageContainer.className = "message"
messageContainer.style.top = `${queue.length * 50}px`
document.body.appendChild(messageContainer)
const root = ReactDom.createRoot(messageContainer)
root.render(<Message />) //渲染组件
queue.push({
messageContainer,
root,
})
//2秒后移除
setTimeout(() => {
const item = queue.find(
(item) => item.messageContainer === messageContainer
)!
item.root.unmount() //卸载
document.body.removeChild(item.messageContainer)
queue.splice(queue.indexOf(item), 1)
}, 2000)
}
//声明扩充
declare global {
interface Window {
onShow: () => void
}
}
export default Message
import './components/Message/index.tsx' at Main.tsx injection
App.tsxCard.tsx
<button onClick={() => window.onShow()}>确认</button>

Component CommunicationsProps
React component uses props to communicate with each other. Each parent component can provide its sub-components with props, thereby transmitting some information to it. Props may remind you of HTML properties, but you can pass any JavaScript values, including objects, arrays and functions, and html elements, which will make our components more flexible.
Get this chapter code https://github.com/message163/react-course/tree/props branch props
For example, when we use the original html label, we can pass the properties for them, as follows:
<img width="500" height="500" alt="xxx" src="xxxxxxx" />
In React, it also allows the transfer of attributes to the Component that you have written as follows:
export default function App() {
return <Card title="标题1" content="内容"></Card>
}
Parent-son component communications
Prepare a Subcomponent Test
const Test = () => {
return <div>Test</div>
}
export default Test
Include this subcomponent in App.tsx
import Test from "./components/Test"
function App() {
return (
<>
<Test></Test>
</>
)
}
export default App
1. Parent-to-child component props
The types of support are as follows:
- string
== sync, corrected by elderman == - number
id={1} - boolean
isGirl={false} - null
empty={null} - undefined
empty={undefined} - object
obj={ { a: 1, b: 2 } } - array
arr={[1, 2, 3]} - function
cb={(a: number, b: number) => a + b} - JSX.Element
== sync, corrected by elderman == @elder man
function App() {
return (
<>
<Test
title={"测试"}
id={1}
obj={{ a: 1, b: 2 }}
arr={[1, 2, 3]}
cb={(a: number, b: number) => a + b}
empty={null}
element={<div>测试</div>}
isGirl={false}
></Test>
</>
)
}
Sub-components subject to parent transfer props
Props is an object that accepts the props values passed as the first parameter of the function
Note: We need to comply with one-way data streams, and subcomponents cannot directly modify props for parent components
Use Object.freezefreeze props to limit props changes in react source code.
Subject.freeze() static method allows an object to be frozen. Freezing objects prevents expansion and renders existing attributes unwritten and non-configurable. The frozen objects can no longer be changed: no new attributes can be added, no existing attributes removed, their amplifiability, configuration, writeability or value can not be changed, nor the prototype of the object can be redesignated
import React from "react"
interface Props {
title: string
id: number
obj: {
a: number
b: number
}
arr: number[]
cb: (a: number, b: number) => number
empty: null
element: JSX.Element
}
const Test: React.FC<Props> = (props) => {
console.log(props)
return <div>Test</div>
}
export default Test
2. Define default values
First way.
Use title for example title?: string for converting properties to optional here
Then deconstruct the props to define the default {title = 'default title '}
import React from "react"
interface Props {
title?: string
id: number
obj: {
a: number
b: number
}
arr: number[]
cb: (a: number, b: number) => number
empty: null
element: JSX.Element
}
const Test: React.FC<Props> = ({ title = "默认标题" }) => {
return <div>Test</div>
}
export default Test
Second way.
Use defaultProps for the default value, and eventually combine the defaultProps with the props, so write the defaultProps first, then the props because the props override the defaultProps.
import React from "react"
interface Props {
title?: string
id: number
obj: {
a: number
b: number
}
arr: number[]
cb: (a: number, b: number) => number
empty: null
element: JSX.Element
}
const defaultProps: Partial<Props> = {
title: "默认标题",
}
const Test: React.FC<Props> = (props) => {
const { title } = { ...defaultProps, ...props }
return <div>{title}</div>
}
export default Test
3. React.FC
React.FC is a functional component, a model used by TS. FC is Function Component's acronym.
React.FC helps us to automatically extrapolate Props types.
Note: In the old version of React.FC contains
PropsWithChildrena new version of the statement is no longer available.
3. Props. Children Special
This function is similar to Vue's slot, and the insertion of a label directly within the subcomponent automatically causes an argument props.children
function App() {
return (
<>
<Test>
<div>123</div>
</Test>
</>
)
}
Subcomponent uses children properties
The previous version of phildren did not need to be defined manually and changed after 18 to need to be defined manually
This will insert the parent <div>123</div> into the subcomponent <div>
import React from "react"
interface Props {
children: React.ReactNode //手动声明children
}
const Test: React.FC<Props> = (props) => {
return <div>{props.children}</div>
}
export default Test
4. Transfer value of sub-components to parent components
React doesn't have an emit-out like Vue. All of us back-to-back functions simulate emit-out.
The parent component conveys Function the past, and the essence of it is the echo of the recruitment function.
import Test from "./components/Test"
function App() {
const fn = (params: string) => {
console.log("子组件触发了 父组件的事件", params)
}
return (
<>
<Test callback={fn}></Test>
</>
)
}
sub-component accepts functions, and calls the function for the corresponding event and returns the parameters
import React from "react"
interface Props {
callback: (params: string) => void
children?: React.ReactNode
}
const Test: React.FC<Props> = (props) => {
return (
<div>
<button onClick={() => props.callback("我见过龙")}>派发事件</button>
</div>
)
}
export default Test
Bro component communication
Defines the two components together as brother components, the rationale of which is the design model Organisation, which is not described here on numerous occasions, and the original browser has achieved this model that we can use directly.
If you don't want to use a primary browser, you can use mitt
mitt document https://www.npmjs.com/package/mitt
import Card from "./components/Card"
import Test from "./components/Test"
function App() {
return (
<>
<Test></Test>
<Card></Card>
</>
)
}
export default App
The first bro component defines the event model
import React from "react"
const Test: React.FC = (props) => {
const event = new Event("on-card") //添加到事件中心
const clickTap = () => {
console.log(event)
event.params = { name: "我见过龙" }
window.dispatchEvent(event) //派发事件
}
return (
<div>
<button onClick={clickTap}>派发事件</button>
</div>
)
}
//扩充event类型
declare global {
interface Event {
params: any
}
}
export default Test
Second brother component accepted.
import "./index.css"
export default function Test2() {
//接受参数
window.addEventListener("on-card", (e) => {
console.log(e.params, "触发了")
})
return <div className="card"></div>
}
React Controlled Component Understanding and Application
React Controlled Component
Controlled components generally refer to graphs, whose data are managed by React 's State, and when updating the data, it is required to manually call the setstate() method to update the data. Because React does not have a v-model like Vue, it is necessary to achieve the binding event itself.
Then why use controlled components?
The use of controlled components ensures that the form data are synchronized with the condition of the component, that they are centrally managed and validated, and that flexible event-handling mechanisms are provided for data formatting and UI-activation.
Cases
We enter in the interface input box, and then you find the value is read-only, unmodifiable and faulty.
hook.js:608 You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly. Error Component Stack
import React, { useState } from "react"
const App: React.FC = () => {
const [value, setValue] = useState("")
return (
<>
<input type="text" value={value} />
<div>{value}</div>
</>
)
}
export default App
When the user enters the content, it does not automatically update the value, which requires us to update it manually by achieving an onChange event.
import React, { useState } from "react"
const App: React.FC = () => {
const [value, setValue] = useState("")
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
}
return (
<>
<input type="text" value={value} onChange={handleChange} />
<div>{value}</div>
</>
)
}
export default App
In fact, a Vue-like v-mode mechanism was put in place to update the vue through the OnChange incident, which led to the achievement of controlled components.
:::tip Controlled components apply to all tablet units, including input, texttarea, selfct, etc. However, except for input type = "file " , other tabulars are recommended for controlled components. :::
React Uncontrolled Component
The uncontrolled component means that the matrix is not managed by the state of React, and the data on the form is managed by DOM. The values of the table cells are obtained by using Ref().
Look at the VCR.
We use defaultValue to set the default value for the form, but if you want to get the value in real time, you need to use the useRef() to get the value of the table unit. Same as running Dom.
import React, { useState, useRef } from "react"
const App: React.FC = () => {
const value = "小满"
const inputRef = useRef<HTMLInputElement>(null)
const handleChange = () => {
console.log(inputRef.current?.value)
}
return (
<>
<input
type="text"
onChange={handleChange}
defaultValue={value}
ref={inputRef}
/>
</>
)
}
export default App
Special Form File
For a table control of a file type, it is a special component because its value can only be set by the user through a file selection operation and not directly by the program. This makes it treats it differently from other tabular cells in React.
Look at the VCR.
If you have to set the file type as a controlled component, he'll be able to report. Wrong.
hook.js:608 A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info:
The error is roughly:
:::danger A component is replacing an uncontrolled input control with a controlled one. This may be because the value has never been defined and this should not happen. The use of controlled or uncontrolled input controls is determined during the life cycle of the component. :::
import React, { useState } from "react"
const App: React.FC = () => {
const [files, setFiles] = useState<File | null>(null)
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFiles(e.target.files?.[0]!)
}
return (
<>
<input type="file" value={files} onChange={handleChange} />
</>
)
}
export default App
Modify to Uncontrolled Component
import React, { useRef } from "react"
const App: React.FC = () => {
const inputRef = useRef<HTMLInputElement>(null)
const handleChange = () => {
console.log(inputRef.current?.files)
}
return (
<>
<input type="file" ref={inputRef} onChange={handleChange} />
</>
)
}
export default App
createPortal
Note that this is an API, not a component, whose role is to render a component to any location of Dom, similar to the Teleport component of Vue.
Usage
import { createPortal } from "react-dom"
const App = () => {
return createPortal(<div>小满zs</div>, document.body)
}
export default App
Parameters
Participation
- Children: components to render
- DomNode: To render Dom position
- Key?: optional, for the only component to identify to render
Return value
- Returns a react element (i.e. jsx) which can be rendered by React at any location of Dom
Apply scene
- Blast the window.
- Down Frame
- Global tip
- Global Mask
- Global Loating
Antd's Modal component, for example, is mounted on body.

Cases
Encapsulated bullet frame components
- src/components/Modal/index.tsx
import "./index.css"
export const Modal = () => {
return (
<div className="modal">
<div className="modal-header">
<div className="modal-title">标题</div>
</div>
<div className="modal-content">
<h1>Modal</h1>
</div>
<div className="modal-footer">
<button className="modal-close-button">关闭</button>
<button className="modal-confirm-button">确定</button>
</div>
</div>
)
}
- src/components/Modal/index.css
.modal {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 1px solid #4d4d4d;
width: 500px;
height: 400px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
padding: 20px;
border-radius: 5px;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-title {
font-size: 1.5rem;
font-weight: bold;
}
.modal-content {
padding: 20px 0;
flex: 1;
}
.modal-footer {
display: flex;
justify-content: flex-end;
}
.modal-close-button {
margin-right: 10px;
background-color: #000;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
.modal-confirm-button {
margin-left: 10px;
background-color: rgb(46, 46, 164);
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
Basic html + css.

If there is a postion: relative style on the outer layer, then the frame will be positioned relative to the outer layer, and if there is no postion: relative style on the outer layer, then the frame will be positioned relative to the body, so the Modal is unstable, so there is a need to use filePortal to mount Modal onto the body, or to change the position directly to a position: fixed.
- Option I: Use CreatePortal
import "./index.css"
import { createPortal } from "react-dom"
export const Modal = () => {
return createPortal(
<div className="modal">
<div className="modal-header">
<div className="modal-title">标题</div>
</div>
<div className="modal-content">
<h1>Modal</h1>
</div>
<div className="modal-footer">
<button className="modal-close-button">关闭</button>
<button className="modal-confirm-button">确定</button>
</div>
</div>,
document.body
)
}
- Option II: Use position: fixed
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 1px solid #4d4d4d;
width: 500px;
height: 400px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
padding: 20px;
border-radius: 5px;
display: flex;
flex-direction: column;
justify-content: space-between;
}
In this way, the Modal component stabilizes, and regardless of whether the outer layer has a style of position: relative, the Modal component locates against the body.
Small words.
I would prefer to use createPortal because he is more flexible and can be mounted in any position, and position: fixed will have a lot of problems. By default, he locates according to the browser viewer, but if the parent sets Transform, perspective, filler or backdrop-file properties that are not none, he locates in relation to the parent, which will lead to an inaccurate location of the Modal component He doesn't always follow the viewer. I'm not sure. and is not recommended for use.
Suspense
Suspense is an anecdotal rendering mechanism whose core concept is to display a placeholder (loading state) in the process of loading components or data acquisition, thus bringing about a more natural and fluid user interface update.
Apply scene
-
** The heavy component is loaded**: the component is loaded on demand through a code subcontract that effectively reduces the volume of resources when the first screen is loaded and enhances application performance.
-
** Theatrical data load**: the display of elegant transitions (e.g., loating animations, skeleton screens, etc.) in the data request provides a more fluid interactive experience for users.
-
**Stepshot resources loaded **: Smartly manage the load status of photographic resources, display location content before the picture is fully loaded, ensure a stable page layout and enhance user experience.
Usage
<Suspense fallback={<div>Loading...</div>}>
<AsyncComponent />
</Suspense>
Participation:
- Fallback: Specifies the component or element displayed during the component loading or data acquisition
- Children: Specify the component or data to load by walk
Cases
Step Component Load
Create a rectangular component
- src/components/Async/index.tsx
export const AsyncComponent = () => {
return <div>Async</div>
}
export default AsyncComponent
- src/App.tsx
Use lazy for insular load components, use Suspense to wrap in an ambulatory component and fallback to specify the placed components during loading
import React, { useRef, useState, Suspense, lazy } from "react"
const AsyncComponent = lazy(() => import("./components/Async"))
const App: React.FC = () => {
return (
<>
<Suspense fallback={<div>loading</div>}>
<AsyncComponent />
</Suspense>
</>
)
}
export default App
The effects were as follows:
:::tip You can adjust the network to slow speed. You can see the effect of loating. :::


Step Data Loading
We achieve card details by displaying the skeleton screen during data loading and the card details when data loading is completed.
:::tip
It's recommended to be upgraded to React19 because we're going to use an API at use, which is an experimental feature at React18, to include a formal feature at React19.
:::
Simulating data, we put it in the public directory, to facilitate direct access (by address + filename), for example:
http://localhost:5173/data.json
- public/data.json
{
"data": {
"id": 1,
"address": "北京市房山区住岗子村10086",
"name": "小满",
"age": 26,
"avatar": "https://api.dicebear.com/7.x/avataaars/svg?seed=小满"
}
}
Create a skeleton screen component for displaying and enhancing user experience during data loading, and of course you can seal up the loating component.
- src/components/skeleton/index.tsx
import "./index.css"
export const Skeleton = () => {
return (
<div className="skeleton">
<header className="skeleton-header">
<div className="skeleton-name"></div>
<div className="skeleton-age"></div>
</header>
<section className="skeleton-content">
<div className="skeleton-address"></div>
<div className="skeleton-avatar"></div>
</section>
</div>
)
}
.skeleton {
width: 300px;
height: 150px;
border: 1px solid #d6d3d3;
margin: 30px;
border-radius: 2px;
}
.skeleton-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #d6d3d3;
padding: 10px;
}
.skeleton-name {
width: 100px;
height: 20px;
background-color: #d6d3d3;
animation: skeleton-loading 1.5s ease-in-out infinite;
}
.skeleton-age {
width: 50px;
height: 20px;
background-color: #d6d3d3;
animation: skeleton-loading 1.5s ease-in-out infinite;
}
.skeleton-content {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.skeleton-address {
width: 100px;
height: 20px;
background-color: #d6d3d3;
animation: skeleton-loading 1.5s ease-in-out infinite;
}
.skeleton-avatar {
width: 50px;
height: 50px;
background-color: #d6d3d3;
animation: skeleton-loading 1.5s ease-in-out infinite;
}
@keyframes skeleton-loading {
0% {
opacity: 0.6;
}
50% {
opacity: 1;
}
100% {
opacity: 0.6;
}
}
Create a card component to display data, which introduces a new API use
use API used to obtain Promise inside the component, or Context content, using the use to obtain data on Promise's return and deliberately delayed return for 2 seconds to simulate a web request.
- src/components/Card/index.tsx
import { use } from "react"
import "./index.css"
interface Data {
name: string
age: number
address: string
avatar: string
}
const getData = async () => {
await new Promise((resolve) => setTimeout(resolve, 2000))
return (await fetch("http://localhost:5173/data.json").then((res) =>
res.json()
)) as { data: Data }
}
const dataPromise = getData()
const Card: React.FC = () => {
const { data } = use(dataPromise)
return (
<div className="card">
<header className="card-header">
<div className="card-name">{data.name}</div>
<div className="card-age">{data.age}</div>
</header>
<section className="card-content">
<div className="card-address">{data.address}</div>
<div className="card-avatar">
<img width={50} height={50} src={data.avatar} alt="" />
</div>
</section>
</div>
)
}
export default Card
.card {
width: 300px;
height: 150px;
border: 1px solid #d6d3d3;
margin: 30px;
border-radius: 2px;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #d6d3d3;
padding: 10px;
}
.card-age {
font-size: 12px;
color: #999;
}
.card-content {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
(b) Package the Card component through Suspense, and assign the skeleton screen component to Fallback
- src/App.tsx
import React, { useRef, useState, Suspense, lazy } from "react"
import Card from "./components/Card"
import { Skeleton } from "./components/Skeleton"
const App: React.FC = () => {
return (
<>
<Suspense fallback={<Skeleton />}>
<Card />
</Suspense>
</>
)
}
export default App
The effects were as follows:

Combat component
:::warning
This chapter suggests that you take a look at these chapters after hooks css Component, which would be better understood.
:::
This chapter is additionally new, as the knowledge of previous years is almost universal, so it is primarily about making it work and consolidating it.
So what will you learn?
- How to achieve a
Treecomponent - Usage of Recursive Component
- Component Library Cover
- Front-end package format
UMDESMCJS - Component library release
npm
Directory Create
- dist
Pack up the file. - docs
Document - packages
Component- Tree
- index.ts
Entry - tree.tsx
Component - styles.css
Styles - type.ts
Type
- index.ts
- Button
- index.ts
Entry - button.tsx
Component - styles.css
Styles - type.ts
Type
- index.ts
- index.ts
Component Summary - vite.d.ts
Type
- Tree
- example
- index.html
Example: - App.tsx
Example: - main.tsx
Example:
- index.html
- package.json
Package Management - vite.config.ts
Vite Configuration - tsconfig.json
ts Configuration - README.md
README
:::tip Package.json
tsconfig.json can be generated by tsc --init
:::
The kind of dependency you need.
npm install vite -D # vite 构建工具
npm install @vitejs/plugin-react-swc -D # 插件编译React
npm install vite-plugin-dts -D #生成d.ts文件 声明文件
npm install react #react依赖
npm install react-dom #react依赖
npm install @types/react -D # 类型
npm install @types/react-dom -D # 类型
npm install @types/node -D # 类型
Initialise File
- example/App.tsx
export default function App() {
return <div>Hello World</div>
}
- example/main.tsx
import React from "react"
import ReactDOM from "react-dom/client"
import App from "./App"
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<App />
)
- example/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>example</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
Because vite defaults to find index.html files from the root directory, but our project structure is example/index.html, so we need to configure vite.config.ts
- vite.config.ts
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react-swc"
import path from "node:path"
export default defineConfig({
plugins: [react()],
root: path.resolve(__dirname, "example"),
server: {
port: 3000,
open: true,
},
})
- tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "NodeNext",
"jsx": "preserve",
"jsxImportSource": "react",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["packages/**/*", "vite.config.ts"]
}
- package.json
{
"scripts": {
"dev": "vite",
"build": "vite build"
}
}
Core logical development
- First, a declaration document needs to be defined,
TreeNodedefining the type of each leaf node,TreePropsdefining the properties of the component
- packages/Tree/type.ts
export interface TreeNode {
id: string | number //id用于绑定key
name: string //name用于显示
children?: TreeNode[] //children用于存储子节点
selected: boolean //selected用于存储节点是否选中
}
export interface TreeProps {
data: TreeNode[] //数据源
onChecked: (node: TreeNode) => void //选中回调
}
- The core idea for the realization of the components is to return, and if
childrenappears, continue to revert to itself.
- packages/Tree/tree.tsx
import React, { useState } from "react"
import "./styles.css"
import type { TreeProps, TreeNode } from "./type"
const Tree: React.FC<TreeProps> = ({ data, onChecked }) => {
const [treeData, setTreeData] = useState(data)
const changeSelected = (
e: React.ChangeEvent<HTMLInputElement>,
item: TreeNode
) => {
setTreeData(
treeData.map((node) =>
node.id === item.id ? { ...node, selected: e.target.checked } : node
)
) // 更新选中状态
onChecked && onChecked({ ...item, selected: e.target.checked }) // 触发回调
}
return (
<div>
{treeData.map((item) => {
return (
<div key={item.id}>
<input
onChange={(e) => changeSelected(e, item)}
type="checkbox"
checked={item.selected}
/>
<span>{item.name}</span>
<div className="tree-node">
{item.children && (
<Tree data={item.children} onChecked={onChecked}></Tree>
)}
</div>
</div>
)
})}
</div>
)
}
export default Tree
- Preparation of style files (mainly for some margins)
- packages/Tree/styles.css
.tree-node {
margin-left: 10px;
padding: 10px;
}
- Entry files for components (required to export components and types for ease of use)
- packages/Tree/index.ts
import Tree from "./tree"
export * from "./type"
export { Tree }
- Summary file of components (requires export of components and types for ease of use)
- packages/index.ts
import { Tree } from "./Tree"
import { Button } from "./Button" //例子
import { Input } from "./Input" //例子
export * from "./Tree"
export * from "./Button" //例子
export * from "./Input" //例子
export { Tree, Button, Input }
- App.tsx
import React from "react"
import { Tree, type TreeNode } from "../packages"
export default function App() {
const data: TreeNode[] = [
{
id: "1",
name: "parent-1",
selected: false,
children: [
{
id: "1-1",
name: "child-1-1",
selected: false,
children: [{ id: "1-1-1", name: "child-1-1-1", selected: false }],
},
],
},
{
id: "2",
name: "parent-2",
selected: true,
children: [
{
id: "2-1",
name: "child-2-1",
selected: true,
children: [{ id: "2-1-1", name: "child-2-1-1", selected: true }],
},
],
},
]
return (
<div>
<Tree
data={data}
onChecked={(data: TreeNode) => {
console.log(data)
}}
></Tree>
</div>
)
}

Pack up for distribution
It's a rollup in the vite, so it's easy to pack. dts plugins are used to generate type files (declaration files). Profile description:
- OutDir: Packed Folders
- lib: Packing configuration
- Formats: Packing format (es/umd/cjs)
- FileName: Packed Files First Name
- Root: The development environment is example, according to the environment, and is the root directory when packed
- RollupOptions: Rollup Configuration
- External: Neglected dependency (user project installed)
- Globals: global variable configuration
Es is esModule, umd is the global variable that contains amd and cjs, cjs is commonjs, iife is the immediate execution function.
- vite.config.ts
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react-swc"
import path from "node:path"
import dts from "vite-plugin-dts"
export default defineConfig(({ command }) => {
const isDev = command === "serve"
return {
plugins: [
react(),
dts({
outDir: path.resolve(__dirname, "dist"),
insertTypesEntry: true, //这是dts插件的配置,用于生成类型文件
include: ["packages/**/*.ts", "packages/**/*.tsx"],
rollupTypes: true,
}),
],
root: isDev ? path.resolve(__dirname, "example") : undefined,
server: {
port: 3000,
open: true,
},
build: {
outDir: path.resolve(__dirname, "dist"),
lib: {
entry: path.resolve(__dirname, "packages/index.ts"),
name: "ui",
formats: ["es", "umd", "cjs", "iife"],
fileName: (format) => `ui.${format}.js`,
},
emptyOutDir: false,
rollupOptions: {
external: ["react", "react-dom"],
output: {
globals: {
react: "React",
"react-dom": "ReactDOM",
},
},
},
},
}
})
Configure package.json
- Name: Package Name (name on npm)
- Version: Version
- File to upload to npm (dist to npm here)
- Main: cjs entrance
- Module: esm entrance
- typees: type files

Publish Npm
- No account number to register a
npm addusernpm official network - Enter account password for login
npm login - Once
npm publishis released, you can search your bag on npm.

Install Test
npm install xm-ui-react-1
Just one file.
import React from 'react';
import { Tree } from 'xm-ui-react-1'
import 'xm-ui-react-1/dist/xm-ui-react.css'
const App: React.FC = () => {
const data = [
{
id: '1',
name: 'parent-1',
selected: true,
children: [
{
id: '2',
name: 'child-2',
selected: true,
children: [
{
id: '3',
name: 'child-3',
selected: true,
}
]
}
]
},
{
id: '4',
name: 'parent-4',
selected: true,
children: [
{
id: '5',
name: 'child-5',
selected: true,
children: [
{
id: '6',
name: 'child-6',
selected: true,
}
]
}
]
}
]
return (
<>
<Tree onChecked={console.log} data={data}></Tree>
</>
);
}
export default App;

HOC (Higger Order Component) high-level component
:::warning This chapter is optional.
- When you're using the Hooks, the HOC scene will shrink.
- Why do you have to ask when you're interviewing? Down
- Knowledge of relevant norms does not prevent theoretical understanding of actual project development :::
What's a high-level component?
A high-level component is a component, which accepts another component as a parameter and returns to a new component. (If you learn Vue, it's a bit similar to the secondary encapsulation component in Vue), the new component can reproduce the logic of the old component and add new functions. Often used in class components, although it is now all hooks writing that reduces the use of HOC, some of the scenes will be used at Because people are dead, the code is alive, it has to be flexible..
Introduction
** Watch out**
- HOC does not modify incoming components, but uses a combination to achieve functional expansion by wrapping the original components in a container component
- Be careful to avoid multilayering. General HOC does not have more than three layers.
- HOC naming code:
withbeginning, e.g.withLoading,withAuthetc.
** Example of code**
We use an example of competence to get to the HOC, and we can replicate this logic with flexibility.
enum Role {
ADMIN = "admin",
USER = "user",
}
const withAuthorization = (role: Role) => (Component: React.FC) => {
// 判断是否具有权限的函数
const isAuthorized = (role: Role) => {
return role === Role.ADMIN
}
return (props: any) => {
// 判断是否具有权限
if (isAuthorized(role)) {
//把props透传给组件
return <Component {...props} />
} else {
// 没有权限则返回一个提示
return <div>抱歉,您没有权限访问该页面</div>
}
}
}
const AdminPage = withAuthorization(Role.ADMIN)(() => {
return <div>管理员页面</div> //有权限输出
})
const UserPage = withAuthorization(Role.USER)(() => {
return <div>用户页面</div> //没有权限不输出
})
Progress use
Covers a common HOC to achieve location statistics, such as click events, page mounted, page unmounting, etc.
Encapsulating a burial site service can expand on its own business.
trackTypeindicates the type of component to send the burial sitedataindicates the data senteventDataindicates user behaviour data to be measurednavigator.sendBeaconis a safe and reliable walk-by data transfer from browser that is suitable for sending small amounts of data, such as buried point data, and when browsers are closed, data is sent without blocking page loading
const trackService = {
sendEvent: <T>(trackType: string, data: T = null as T) => {
const eventData = {
timestamp: Date.now(), // 时间戳
trackType, // 事件类型
data, // 事件数据
userAgent: navigator.userAgent, // 用户代理
url: window.location.href, // 当前URL
}
//发送数据
navigator.sendBeacon("http://localhost:5173", JSON.stringify(eventData))
},
}
High-level HOC components are achieved, mounted and unmounted through the use of Effect statistical components, and a trackEvent method is sealed and passed to sub-components, which can be called by themselves and measure user behaviour.
const withTrack = (Component: React.ComponentType<any>, trackType: string) => {
return (props: any) => {
useEffect(() => {
//发送数据 组件挂载
trackService.sendEvent(`${trackType}-MOUNT`)
return () => {
//发送数据 组件卸载
trackService.sendEvent(`${trackType}-UNMOUNT`)
}
}, [])
//处理事件
const trackEvent = (eventType: string, data: any) => {
trackService.sendEvent(`${trackType}-${eventType}`, data)
}
return <Component {...props} trackEvent={trackEvent} />
}
}
Using the HOC high-level component, a Button button is registered and a trackEvent method is passed, so the sub-component can be called on its own and measure user behaviour.
const Button = ({ trackEvent }) => {
// 点击事件
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
trackEvent(e.type, {
name: e.type,
type: e.type,
clientX: e.clientX,
clientY: e.clientY,
})
}
return <button onClick={handleClick}>我是按钮</button>
}
// 使用HOC高阶组件
const TrackButton = withTrack(Button, "button")
// 使用组件
const App = () => {
return (
<div>
<TrackButton />
</div>
)
}
export default App
Preview of reported data formats (which can be extended or modified on their own initiative)

css programmes
css modules
What's css modules?
Because React does not have a Vue Scoped, but React is also a SPA (single page application) so a way is needed to resolve the problem of csss style conflicts, i.e., to separate the styles of each component into a separate domain, and css modules is a solution, but we need to use tools such as webpack, postcss, css-loader, vite, etc.
How to use css modules in Vite
css modules, which can be used in conjunction with various css pre-treatments such as less, sass, stylus, etc.
npm install less -D # 安装less 任选其一
npm install sass -D # 安装sass 任选其一
npm install stylus -D # 安装stylus 任选其一
::: tip In Vite, css Modules is for open boxes, with `xxx.module.[css]|less|sass|. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . :::
- src/components/Button/index.module.scss
.button {
color: red;
}
- src/components/Button/index.tsx
//使用方法,直接引入即可
import styles from "./index.module.scss"
export default function Button() {
return <button className={styles.button}>按钮</button>
}
- As a result of the compilation, you can see that the
buttonclass name has been compiled intobutton_pmkzx_6, which is the principle of css modules, by adding a unique Hash value to the category to isolate the style.
<button class="button_pmkzx_6">按钮</button>
Modify css rules
- Configure css rules in vite.config.ts
export default defineConfig({
css: {
modules: {
localsConvention: "dashes", // 修改css modules的类名规则 可以改成驼峰命名 或者 xxx-xxx命名等
generateScopedName: "[name]__[local]___[hash:base64:5]", // 修改css modules的类名规则
},
},
})
For example, it's set to name (localsConvention:camelCaseOnly) the camel.
::: warning The difference between camelCase and camelCaseOnly is that camelCase converts the name of a non-camel peak to a camel, and preserves the previous class name, while camelCaseOnly only converts the name of a non-camelCamelCaseOnly to a camel and deletes the previous class name. :::
- src/components/Button/index.module.scss
.button-red {
color: red;
}
- src/components/Button/index.tsx
::: tip
Set to post-camel peaks, which need to be named after them, for example buttonRed, rather than button-red.
:::
import styles from "./index.module.scss"
export default function Button() {
return <button className={styles.buttonRed}>按钮</button>
}
For example, setting (localsConvention:dashesOnly) would convert all -- all -- class names into camels, and the original class names would be deleted.
::: warning The difference between Dashes and DashesOnly is that Dashes will keep the original class name, and DashesOnly will delete the original class name. :::
- src/components/Button/index.module.scss
.button-red {
color: red;
}
- src/components/Button/index.tsx
::: tip
When set to be the original name, it is to be used with a hump, for example buttonRed, rather than button-red.
:::
import styles from "./index.module.scss"
export default function Button() {
return <button className={styles.buttonRed}>按钮</button>
}
::: info
If you want to support the name of the hump and the - connection at the same time, you can set it to localsConvention:[camelCase|dashes], so you can also support the name of the - .
:::
Example: Change the class name rule for css modules
- Configure css rules in vite.config.ts
export default defineConfig({
css: {
modules: {
generateScopedName: '[local]_[hash:base64:5]' // 只保留类名和哈希值
// 或者
generateScopedName: '[hash:base64:8]' // 只使用哈希值
// 或者
generateScopedName: '[name]_[local]' // 只使用文件名和类名,没有哈希
// 或者
generateScopedName: '[local]--[hash:base64:4]' // 自定义分隔符
},
},
});
Compilation Results
<button class="button_pmkzx_6">类名 + 哈希值</button>
<button class="pmkzx_6">哈希值</button>
<button class="index-module_button">文件名 + 类名</button>
<button class="button--pmkzx_6">类名 + 分隔符 + 哈希值</button>
Maintenance of class names
This means that certain styles in style files that do not want to be compiled into cssmudules can be set to global, for example:
.app {
background: red;
width: 200px;
height: 200px;
:global(.button) {
background: blue;
width: 100px;
height: 100px;
}
}
//在使用的时候,就可以直接使用原始的类名 button
import styles from "./index.module.scss"
const App: React.FC = () => {
return (
<>
<div className={styles.app}>
<button className="button">按钮</button>
</div>
</>
)
}
css-in-js
css-in-js is to mix the CSS code with the JS code to dynamically generate the CSS style through JS, but that would run counter to our perception that the CSS JS HTML should be separated, but because the CSS lacked a role field, the css-in-js formulation was developed, noting that css-in-js is not a technology, but an idea.
It's called the three front-end pieces, and it's a long-term one.
Advantages and disadvantages
Advantages:
- CSS can be given an independent domain to prevent CSS from leaking to the outside of the components and preventing conflict.
- CSS styles can dynamically generate CSS styles, depending on the status of the component.
- CSS-in-JS can easily achieve a subject-to-theme switch, with changes to the subject-variant to change the entire application style.
Disadvantages:
- csss-in-js is run-time-based, so some performance is lost (computer performance is negligible)
- Debugging difficulties make it difficult to debug the CSS-in-JS styles because they are dynamically generated and not defined in the CSS file.
Who's using it?
- The most common is the
Antdself-studycss-in-jslibrary
There are many css-in-js libraries, such as styled-components, emotion, etc., because it is only a thought, so many of them have achieved it, but the way they are achieved is different, so they need to be used to choose the appropriate library according to the circumstances, so Antd has chosen self-study.

Cases
We take the example of styled-components to achieve a simple css-in-js case.
:::tip Stilled-components Network :::
- Install
styled-components
npm install styled-components
- Create a
Buttoncomponent
import React from "react"
import styled from "styled-components"
const Button = styled.button<{ primary?: boolean }>`
${(props) => (props.primary ? "background: #6160F2;" : "background: red;")}
padding: 10px 20px;
border-radius: 5px;
color: white;
cursor: pointer;
margin: 10px;
&:hover {
color: black;
}
`
const App: React.FC = () => {
return (
<>
<Button primary>按钮</Button>
</>
)
}
export default App

As we can see, Button components are randomly created by js, thus avoiding the problem of class conflicts.
More use
Succession
We can achieve a basic Button component, and then more button styles by inheritance.
For example, the ButtonBase component in the example, which is then achieved on the basis of the basic styles, BlueButton, FailButton, TextButton components, which facilitate the re-use of the basic styles and fast-assembling components.
import React from "react"
import styled from "styled-components"
const ButtonBase = styled.button`
padding: 10px 20px;
border-radius: 5px;
color: white;
cursor: pointer;
margin: 10px;
&:hover {
color: red;
}
`
//圆角蓝色按钮
const BlueButton = styled(ButtonBase)`
background-color: blue;
border-radius: 20px;
`
//失败按钮
const FailButton = styled(ButtonBase)`
background-color: red;
`
//文字按钮
const TextButton = styled(ButtonBase)`
background-color: transparent;
color: blue;
`
const App: React.FC = () => {
return (
<>
<BlueButton>普通按钮</BlueButton>
<FailButton>失败按钮</FailButton>
<TextButton>文字按钮</TextButton>
</>
)
}
export default App

Properties
We can add properties to components by attrs, for example defaultValue, and then get attribute values by props.
import React from "react"
import styled from "styled-components"
interface DivComponentProps {
defaultValue: string
}
const InputComponent = styled.input.attrs<DivComponentProps>((props) => ({
type: "text",
defaultValue: props.defaultValue,
}))`
border: 1px solid blue;
margin: 20px;
`
const App: React.FC = () => {
const defaultValue = "小满zs"
return (
<>
<InputComponent defaultValue={defaultValue}></InputComponent>
</>
)
}
export default App
Global Styles
We can create a global style by createGlobalStyle and then put it in App components.
import React from "react"
import styled, { createGlobalStyle } from "styled-components"
const GlobalStyle = createGlobalStyle`
body {
background-color: #f0f0f0;
},
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul,ol{
list-style: none;
}
`
const App: React.FC = () => {
return (
<>
<GlobalStyle />
</>
)
}
export default App
Animation
We can create animations by keyframes.
import React from "react"
import styled, { createGlobalStyle, keyframes } from "styled-components"
const move = keyframes`
0%{
transform: translateX(0);
}
100%{
transform: translateX(100px);
}
`
const Box = styled.div`
width: 100px;
height: 100px;
background-color: red;
animation: ${move} 1s linear infinite;
`
const App: React.FC = () => {
return (
<>
<Box></Box>
</>
)
}
export default App
Principle Parsing
This technology, called Tab Template, is an additional feature of the ES6 that can be followed by a function that will be used to call this string template
After the call is completed, the first parameter of this function is the static string of the template string, starting with the second parameter, which is the variable value in the template string, which is the value in ${}
strArr:['\n color:red;\n width:', 'px;\n height:', 'px;\n', raw: Array(3)]args:[30, 50]
const div = function (strArr: TemplateStringsArray, ...args: any[]) {
return strArr.reduce((result, str, i) => {
return result + str + (args[i] || "")
}, "")
}
const a = div`
color:red;
width:${30}px;
height:${50}px;
`
console.log(a)
// 输出结果
// color:red;
// width:30px;
// height:50px;
Atomicized csss
What's atomized css?
Atomized CSS is a modern CSS development method that divides the CSS style into the smallest, single functional category. For example, one class only sets colours and the other only sets margins. This approach makes the style easier to maintain and reuse, increases development efficiency and reduces code redundancy. By combining these small style groups, you can build complex interface components.
Atomization csss Basic Concepts
Atomized css is a programming paradigm for csss, which divides the css style into the smallest units, each of which is a separate css category, to construct a whole page style through these separate csss classes, for example:
:::tip The core idea is to define complex interface components by combining these small style groups without having to repeat them. :::
<style>
.color-red {
color: red;
}
.text-center {
text-align: center;
}
.p-10 {
padding: 10px;
}
</style>
<section class="bg-red p-10 text-center">原子化 css</section>

So who's using it?
For example, the more well-known websites are: x Github, where they use atomized css to construct their websites.


TailWind Css
TailWind is a way to achieve atomization of csss, which contains a number of class classes of fine particles that can be used in combination to construct complex interface components.
How to use TailWind Css.
- Vite Item
npm install tailwindcss @tailwindcss/vite
- vite.config.ts
Introduce tailwindcss plugins and configure tailwindcss plugins
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react-swc"
import tailwindcss from "@tailwindcss/vite"
export default defineConfig({
plugins: [react(), tailwindcss()],
})
- (New file)
Introducing
tailwindcssStyles
@import "tailwindcss";
- src/main.tsx
Introducing tailwindcss Styles
import "./tailwind.css"
- src/App.tsx
Try the
tailwindcssstyle
<section class="bg-red p-10 text-center">原子化 css</section>
- Opens Vscode or Cursor and installs
TailWind Cssplugins so that when writing codes, you will automatically indicatetailwindcssstyles

Cases
Simple use tailwindcss to construct a welcome Page
import React from "react"
const App: React.FC = () => {
return (
<>
<div className="flex h-screen w-screen items-center justify-center bg-gradient-to-r from-pink-600 to-purple-600">
<div className="text-4xl font-bold text-white hover:text-gray-300">
大家好我是小满zs,欢迎来到我的博客
</div>
</div>
</>
)
}
export default App

Progress Usage
We can see that many of these codes are stacked together, so it's not pretty, and we can use tailwindcss @apply to solve this problem.
- src/tailwind.css
@import "tailwindcss";
.blob-bg {
@apply flex h-screen w-screen items-center justify-center bg-gradient-to-r from-pink-600 to-purple-600;
}
.blob-text {
@apply text-4xl font-bold text-white hover:text-gray-300;
}
- src/App.tsx
It's the same, but it looks better.
<div className="blob-bg">
<div className="blob-text">大家好我是小满zs,欢迎来到我的博客</div>
</div>
See Custom Styles for more use
Hooks
Data driver
useState
useState is a React Hook that allows function components to be managed internally.
Components usually need to change the contents displayed on the screen on an interactive basis, for example by clicking on a button, or by entering the contents in the text box, which are referred to as status values (state).
Usage method
useState Receives one parameter, i.e. the initial value of the state, and returns an array containing two elements: Current status value and a function to update the status
const [state, setState] = useState(initialState)
Attention
useState is a Hook, so you can only call it in Top layer of the component or your own Hook. You cannot call it in a circular or conditional statement.
In a strict mode, React will Two Call Initialisation Functions help you find accidental impurity. It's just development behavior, not production.
Usage
Add a Status
const Card = () => {
let [index, setIndex] = useState(0)
let [name, setName] = useState("小满")
let [arr, setArr] = useState([1, 2, 3])
}
Use array decomposition as a rule to name state variables such as [index, setIndex].
usestate returns an array that contains only two entries:
- This status variable is currently
state, initially set for you to initializestate. - Set function, which allows you to change
stateto any other value when responding to interaction.
To update Content on Screen, use the new status to call the set function:
** Call
setfunction updatestatewillRender Component. **
function changeName() {
setName("大满")
}
React stores a new state, re-renders the component with a new value and updates the UI.
Full version of cases (basic data type)
import { useState } from "react"
function App() {
let [name, setName] = useState("小满") //数字 布尔值 null undefined 都可以直接赋值 一样的
const heandleClick = () => {
setName("大满")
}
return (
<>
<button onClick={heandleClick}>更改名称</button>
<div>{name}</div>
</>
)
}
export default App
Full version of cases (complex data type)
array
In React, you need to treat arrays as read-only and cannot directly modify the original array, for example, by not calling arr.push() arr.pop().
Below is a reference table for common array operations. When you operate an array in React state, you need to avoid using the left column method, and the first right column method:
| Avoid Usage (changes original array) | Recommended (a new array returns) |
|---|---|
| Add Element Push, unshift | Commat, [...arr] Expand Syntax: (example) |
| Remove Elements Pop, Shift, Spice | (Examples) |
| Replace element splice, arr[i] =... | Map (example) |
| Sort | Copy an array first (example) |
Add Numeric Data
Creates a new array that contains all elements of the original array, and then adds new elements at the end. If you want to add new elements to the head, you can return.
import { useState } from "react"
function App() {
let [arr, setArr] = useState([1, 2, 3])
const heandleClick = () => {
setArr([...arr, 4]) //末尾新增 扩展运算符
//setArr([0,...arr]) 头部新增 扩展运算符
}
return (
<>
<button onClick={heandleClick}>更改值</button>
<div id="aaa">{arr}</div>
</>
)
}
export default App
Other Organiser
Use the fileter to filter out the elements that are not needed.
import { useState } from "react"
function App() {
let [arr, setArr] = useState([1, 2, 3])
const heandleClick = () => {
setArr(arr.filter((item) => item !== 1)) //删除指定元素
}
return (
<>
<button onClick={heandleClick}>更改值</button>
<div id="aaa">{arr}</div>
</>
)
}
export default App
Numerical replacement data
Use Map to select the elements that need to be replaced, and then replace them with new elements, with the other elements remaining unchanged.
import { useState } from "react"
function App() {
let [arr, setArr] = useState([1, 2, 3])
const heandleClick = () => {
setArr(
arr.map((item) => {
return item == 2 ? 666 : item
})
)
}
return (
<>
<button onClick={heandleClick}>更改值</button>
<div id="aaa">{arr}</div>
</>
)
}
export default App
Specify location to insert elements
The case is followed by the insertion of 2.5, by slice, to intercept the elements in front, because slice returns a new array, then inserts the elements we need to insert in the middle, and then removes the elements in the end through slice and closes them behind.
Slice Document https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
import { useState } from "react"
function App() {
let [arr, setArr] = useState([1, 2, 3])
const heandleClick = () => {
let startIndex = 0
let endIndex = 2
setArr([...arr.slice(startIndex, endIndex), 2.5, ...arr.slice(endIndex)])
}
return (
<>
<button onClick={heandleClick}>更改值</button>
<div id="aaa">{arr}</div>
</>
)
}
export default App
Sort rotation, etc.
Case, create a new array, and sort it through soort.
import { useState } from "react"
function App() {
let [arr, setArr] = useState([1, 2, 3])
const heandleClick = () => {
let newList = [...arr].map((v) => v + 1) //拷贝到新数组
newList.sort((a, b) => b - a)
//newList.reverse()旋转
setArr(newList)
}
return (
<>
<button onClick={heandleClick}>更改值</button>
<div id="aaa">{arr}</div>
</>
)
}
export default App
Object
Use State can accept a function in which you can write logic, initialize values, note that this will only be executed once and will not be implemented when it is updated.
When using setObject, you can either merge objects with Object.assign or... merge objects, which cannot be assigned separately, otherwise you will overwhelm the original object.
import { useState } from "react"
function App() {
let [obj, setObject] = useState(() => {
const date =
new Date().getFullYear() +
"-" +
(new Date().getMonth() + 1) +
"-" +
new Date().getDate()
return {
date,
name: "小满",
age: 25,
}
})
const heandleClick = () => {
setObject({
...obj,
name: "大满",
})
//setObject(Object.assign({}, obj, { age: 26 })) 第二种写法
}
return (
<>
<button onClick={heandleClick}>更改值</button>
<div>日期:{obj.date}</div>
<div>姓名:{obj.name}</div>
<div>年龄:{obj.age}</div>
</>
)
}
export default App
Use State update mechanism
The Stepping Mechanism
The use State set function is a step-by-step update to look at the following cases:
import { useState } from "react"
function App() {
let [index, setIndex] = useState(0)
const heandleClick = () => {
setIndex(index + 1)
console.log(index, "index") //0
}
return (
<>
<h1>Index:{index}</h1>
<button onClick={heandleClick}>更改值</button>
</>
)
}
export default App
It's time that index print one, but it's still zero, because the code that we normally write is synchronized, so it's executed first, and the set function is done later with a different pace, and it's done to optimize performance, because we want results, not processes.
Internal mechanisms
When we update the state with the same operation several times, React compares and if the value is the same, block subsequent updates. Bring Wreckproof. functionality to prevent frequent updates.
Case:
import { useState } from "react"
function App() {
let [index, setIndex] = useState(0)
const heandleClick = () => {
setIndex(index + 1) //1
setIndex(index + 1) //1
setIndex(index + 1) //1
console.log(index, "index")
}
return (
<>
<h1>Index:{index}</h1>
<button onClick={heandleClick}>更改值</button>
</>
)
}
export default App
The result is that one is not three, because the value setIndex(index + 1) is the same, and subsequent operations are blocked, preventing an update.
To solve this, you can pass an updated function to setIndex instead of a state.
import { useState } from "react"
function App() {
let [index, setIndex] = useState(0)
const heandleClick = () => {
setIndex((index) => index + 1) //1
setIndex((index) => index + 1) //2
setIndex((index) => index + 1) //3
}
return (
<>
<h1>Index:{index}</h1>
<button onClick={heandleClick}>更改值</button>
</>
)
}
export default App
- index => index + 1 will receive 0 as a pending state and return 1 as the next state.
- index => index +1 will receive 1 as a pending state and return 2 as the next state.
- index => index + 1 will receive 2 as a pending state and return 3 as the next state.
There are no other queuing updates, so React will eventually store 3 as its current status.
In accordance with established practice, the pending status parameter is usually named as the first letter of a status variable name, such as prevIndex or any other name that you think is clearer.
useReducer
useReducer is an advanced Hook provided by React, without which we can develop it properly, but useReducer will make our code more readable and sustainable.
useReducer is the same as useState that helps us manage the component Status, but, unlike useState, useReducer is the management status Focus.
Usage

const [state, dispatch] = useReducer(reducer, initialArg, init?)
Parameters:
-
reduceris a processing function used to update the state, reducer contains two parameters, the first isstateand the second isaction.reducerreturns a newstate. -
initialArgis the initial value ofstate. -
initis an optional function for initializingstateand, if the init function is prepared, the default value uses the return value of the init function, orinitialArg.
Return value:
useReducer returns an array of two values:
Current state. At the first rendering, it is init (initial Arg) or initial Arg (if no init function). Dispatch function. To update the state and trigger the re-rendering of the component.
import { useReducer } from 'react';
//根据旧状态进行处理 oldState,处理完成之后返回新状态 newState
//reducer 只有被dispatch的时候才会被调用 刚进入页面的时候是不会执行的
//oldState 任然是只读的
function reducer(oldState, action) {
// ...
return newState;
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42,name:'小满' });
// ...
Count case
Initial state (initial State):
const initialState = { count: 0 }
This defines an initial status object that contains a count property with an initial value of 0.
Reducer function:
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 }
case "decrement":
return { count: state.count - 1 }
default:
throw new Error()
}
}
- Reducer is a pure function that is used to update the state according to a different action.
- It receives the current status (state) and an action object (action), which determines how to update state according to action. type.
- If action. type is 'increment', count is added 1; if 'development', count is reduced 1.
- If action. type does not match any defined situation, throw an error. App component:
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</>
)
}
export default App
- When clicking on the "-" button, call a dispatch, reduce the count.
- When clicking on the "+" button, call a dispatch ({type: 'increment'}) to increase the count.
Shopping car cases
- Initial data (initData):
const initData = [
{ name: "小满(只)", price: 100, count: 1, id: 1, isEdit: false },
{ name: "中满(只)", price: 200, count: 1, id: 2, isEdit: false },
{ name: "大满(只)", price: 300, count: 1, id: 3, isEdit: false },
]
- InitData is an array representing the initial list of commodities. Each commodity has the following properties:
- Name: The name of the commodity (e.g. "Small (only)).
- Price: Unit price (e.g. 100).
- Count: Number, default is 1.
- id: Only identifier of the commodity.
- isEdit: indicates whether the trade name is edited and defaults to false.
- Type definitions (List and Action):
type List = typeof initData
interface Action {
type: "ADD" | "SUB" | "DELETE" | "EDIT" | "UPDATE_NAME"
id: number
newName?: string
}
- List is the type of commodity array, extrapolated directly from initData.
- Action interface defines different types of operation:
- ADD: Increase the number of a commodity.
- SUB: Reduce the number of a commodity.
- DELETE: Delete a commodity.
- EDIT: Switches the editorial status of a commodity.
- UPDATE NAME: Update the name of a commodity.
- id: id of goods to be operated.
- New Name: New trade name for UPDATE NAME operations.
- Reducer function (reducer):
function reducer(state: List, action: Action) {
const item = state.find((item) => item.id === action.id)!
switch (action.type) {
case "ADD":
item.count++
return [...state]
case "SUB":
item.count--
return [...state]
case "DELETE":
return state.filter((item) => item.id !== action.id)
case "EDIT":
item.isEdit = !item.isEdit
return [...state]
case "UPDATE_NAME":
item.name = action.newName!
return [...state]
default:
return state
}
}
The reducer function updates the status of the list of goods based on the incoming action. Find the product to operate.
Perform corresponding actions for different actions. type:
- ADD: Increase in the number of commodities.
- SUB: Reduced number of commodities.
- DELETE: Delete the specified commodity.
- EDIT: Toggle the editorial status of the commodity (the input box shows or hides).
- UPDATE NAME: Update the name of the commodity.
- App component:
function App() {
let [data, dispatch] = useReducer(reducer, initData)
return (
<>
<table cellPadding={0} cellSpacing={0} width={600} border={1}>
<thead>
<tr>
<th>物品</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{data.map((item) => {
return (
<tr key={item.id}>
<td align="center">
{item.isEdit ? (
<input
onBlur={(e) => dispatch({ type: "EDIT", id: item.id })}
onChange={(e) =>
dispatch({
type: "UPDATE_NAME",
id: item.id,
newName: e.target.value,
})
}
value={item.name}
/>
) : (
<span>{item.name}</span>
)}
</td>
<td align="center">{item.price * item.count}</td>
<td align="center">
<button
onClick={() => dispatch({ type: "SUB", id: item.id })}
>
-
</button>
<span>{item.count}</span>
<button
onClick={() => dispatch({ type: "ADD", id: item.id })}
>
+
</button>
</td>
<td align="center">
<button
onClick={() => dispatch({ type: "EDIT", id: item.id })}
>
编辑
</button>
<button
onClick={() => dispatch({ type: "DELETE", id: item.id })}
>
删除
</button>
</td>
</tr>
)
})}
</tbody>
<tfoot>
<tr>
<td colSpan={3}></td>
<td align="center">
总价:
{data.reduce((prev, next) => prev + next.price * next.count, 0)}
</td>
</tr>
</tfoot>
</table>
</>
)
}
- The App component uses the useReducer to manage the data status, it initializes from initData and changes the list of goods by dispatch distribution.
- The list of goods is rendered by a table displaying the following information for each commodity:
- Items: If the commodity is true, show an input box to modify the name; otherwise, the trade name.
- Price: The total price of the commodity shown (price* country).
- Quantity: Show the number of commodities, provide - and + buttons to reduce or increase the number.
- Operation: Provide Edit buttons to change name editing status, delete buttons to delete the commodity.
- The tfoot part shows the total price of the shopping cart, and the total price of all commodities is calculated using the reduce method.
useImmer

Overview
useImmer is a react Hook based on immer library that allows you to modify non-variable data as you modify variable data. Immer is a non-variable database of data that is fully consistent with the non-variable principle of React.
Core characteristics
- ** Simplified status update**: no manual creation is required to update
- type security: complete TypeScript support
- ** Performance optimization**: creation of new objects only when really needed
- ** Intuitive syntax**: code created as modified variable data
Install
npm install immer use-immer
API Reference
useImmer
function useImmer<S>(
initialState: S | (() => S)
): [S, (f: (draft: Draft<S>) => void | S) => void]
** Parameters:**
initialState: function of initial state value or return to initial state
** Return value:**
state: Current statussetState: Functions for updated status
useImmerReducer
function useImmerReducer<R extends Reducer<any, any>, I>(
reducer: R,
initializerArg: I & InitializerArg<R>,
initializer?: (arg: I & InitializerArg<R>) => ReducerState<R>
): [ReducerState<R>, Dispatch<ReducerAction<R>>]
Guide to use
1. Dealing with nested objects
useImmer is particularly useful when dealing with deep embedded objects and does not need to expand each layer manually:
import { useImmer } from "use-immer"
interface User {
name: string
age: number
profile: {
avatar: string
bio: string
preferences: {
theme: "light" | "dark"
notifications: boolean
}
}
}
export default function UserProfile() {
const [user, setUser] = useImmer<User>({
name: "大满zs",
age: 25,
profile: {
avatar: "/avatar.jpg",
bio: "前端开发者",
preferences: {
theme: "light",
notifications: true,
},
},
})
const updateTheme = () => {
setUser((draft) => {
draft.profile.preferences.theme = "dark"
})
}
const updateBio = (newBio: string) => {
setUser((draft) => {
draft.profile.bio = newBio
})
}
return (
<div className="user-profile">
<h2>{user.name}</h2>
<p>年龄: {user.age}</p>
<p>个人简介: {user.profile.bio}</p>
<p>主题: {user.profile.preferences.theme}</p>
<button onClick={updateTheme}>切换主题</button>
<button onClick={() => updateBio("热爱编程的开发者")}>更新简介</button>
</div>
)
}
2. Processes Group
The array operation becomes extremely simple and all original array methods can be used directly:
import { useImmer } from "use-immer"
interface Todo {
id: number
text: string
completed: boolean
}
export default function TodoList() {
const [todos, setTodos] = useImmer<Todo[]>([])
const addTodo = (text: string) => {
setTodos((draft) => {
draft.push({
id: Date.now(),
text,
completed: false,
})
})
}
const toggleTodo = (id: number) => {
setTodos((draft) => {
const todo = draft.find((t) => t.id === id)
if (todo) {
todo.completed = !todo.completed
}
})
}
const removeTodo = (id: number) => {
setTodos((draft) => {
const index = draft.findIndex((t) => t.id === id)
if (index > -1) {
draft.splice(index, 1)
}
})
}
const clearCompleted = () => {
setTodos((draft) => {
return draft.filter((todo) => !todo.completed)
})
}
return (
<div className="todo-list">
<h2>待办事项 ({todos.length})</h2>
<div className="add-todo">
<input
type="text"
placeholder="添加新待办..."
onKeyPress={(e) => {
if (e.key === "Enter" && e.currentTarget.value.trim()) {
addTodo(e.currentTarget.value.trim())
e.currentTarget.value = ""
}
}}
/>
</div>
<ul>
{todos.map((todo) => (
<li key={todo.id} className={todo.completed ? "completed" : ""}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id)}
/>
<span>{todo.text}</span>
<button onClick={() => removeTodo(todo.id)}>删除</button>
</li>
))}
</ul>
{todos.some((t) => t.completed) && (
<button onClick={clearCompleted}>清除已完成</button>
)}
</div>
)
}
Basic types of treatment
For basic types, useImmer behaviour is fully consistent with useState:
import { useImmer } from "use-immer"
export default function Counter() {
const [count, setCount] = useImmer(0)
const [isVisible, setIsVisible] = useImmer(true)
const increment = () => setCount(count + 1)
const decrement = () => setCount(count - 1)
const reset = () => setCount(0)
const toggleVisibility = () => setIsVisible(!isVisible)
return (
<div className="counter">
{isVisible && (
<>
<h2>计数器: {count}</h2>
<div className="controls">
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
<button onClick={reset}>重置</button>
</div>
</>
)}
<button onClick={toggleVisibility}>
{isVisible ? "隐藏" : "显示"}计数器
</button>
</div>
)
}
Use ImmerReducer
useImmerReducer combines the advantages of useReducer and immer to make the reducer function more concise:
import { useImmerReducer } from "use-immer"
interface State {
count: number
history: number[]
isLoading: boolean
}
type Action =
| { type: "INCREMENT" }
| { type: "DECREMENT" }
| { type: "RESET" }
| { type: "SET_LOADING"; payload: boolean }
| { type: "ADD_TO_HISTORY" }
const initialState: State = {
count: 0,
history: [],
isLoading: false,
}
function counterReducer(draft: State, action: Action) {
switch (action.type) {
case "INCREMENT":
draft.count += 1
break
case "DECREMENT":
draft.count -= 1
break
case "RESET":
draft.count = 0
break
case "SET_LOADING":
draft.isLoading = action.payload
break
case "ADD_TO_HISTORY":
draft.history.push(draft.count)
break
}
}
export default function AdvancedCounter() {
const [state, dispatch] = useImmerReducer(counterReducer, initialState)
const handleIncrement = () => {
dispatch({ type: "SET_LOADING", payload: true })
// 模拟异步操作
setTimeout(() => {
dispatch({ type: "INCREMENT" })
dispatch({ type: "ADD_TO_HISTORY" })
dispatch({ type: "SET_LOADING", payload: false })
}, 500)
}
return (
<div className="advanced-counter">
<h2>高级计数器</h2>
<div className="display">
<span>当前值: {state.count}</span>
{state.isLoading && <span className="loading">加载中...</span>}
</div>
<div className="controls">
<button onClick={handleIncrement} disabled={state.isLoading}>
增加
</button>
<button
onClick={() => dispatch({ type: "DECREMENT" })}
disabled={state.isLoading}
>
减少
</button>
<button
onClick={() => dispatch({ type: "RESET" })}
disabled={state.isLoading}
>
重置
</button>
</div>
{state.history.length > 0 && (
<div className="history">
<h3>历史记录:</h3>
<ul>
{state.history.map((value, index) => (
<li key={index}>{value}</li>
))}
</ul>
</div>
)}
</div>
)
}
Compare with usestate
| Feature | useState | useImmer |
|---|---|---|
| Basic Type | It's simple and straight. | The same experience. |
| Object Update | It needs to go manually. | Direct modification |
| Group Operations | ❌ Need to create a new array | Use of native methods |
| Embedded Update | It's complicated and easy to make mistakes. | It's simple. |
| Performance | Great. | ✅ Excellence |
Attention
- ** Do not directly modify objects outside draft**: Immer can only trace changes in the draft function
- Return value processing: if the updated function returns a value, it replaces the whole state
- Speech operation: close-up when using setstate in stepback
Summary
useImmer is a powerful state management tool that is particularly suited to complex state structures. It makes non-renewal simple intuitive, while maintaining the performance advantage of React. Whether it is a simple counter or a complex form state, useImmer provides an elegant solution.
Related Links
useSyncExternalStore
UseSyncExternalStore is a Hook introduced by React 18 to retrieve the state from external storage (e. g. state management library, browser API etc.) and to synchronize it with the components. This is very useful for applications that need to track the external state.
scene
- Subscription to external store e.g. (redux, Zustand
German) - Subscription to browser API, e. g. (online, source, access)
- Draw out logic, write custom books
- Service render support
Usage
const res = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)
- Subscribe: is used to subscribe to changes in data sources, to receive a callback function, which is called when the data source is updated.
- GetSnapshot: Get a snapshot of the current data source (current status).
- Get ServerSnapshot?
Return value: the current snapshot of the res can be used in your rendering logic
const subscribe = (callback: () => void) => {
// 订阅
callback()
return () => {
// 取消订阅
}
}
const getSnapshot = () => {
return data
}
const res = useSyncExternalStore(subscribe, getSnapshot)
Cases
1. Subscription to browser Api to custom-fix (useStorage)
We achieve a useStorage Hook to subscribe to localStorage data. The advantage of doing this is that we can ensure that components are automatically updated to synchronize when localStorage data changes.
Achieved code
We will create a useStorage Hook that can store data to localStorage and synchronize these states between different browser tabs. This Hook receives a key value parameter for a keyname to store data, and you can also accept a default value for initialization when data are not available.
Defines the useStorage Hook:
import { useSyncExternalStore } from "react"
/**
*
* @param key 存储到localStorage 的key
* @param defaultValue 默认值
*/
export const useStorage = (key: any, defaultValue?: any) => {
const subscribe = (callback: () => void) => {
window.addEventListener("storage", (e) => {
console.log("触发了", e)
callback()
})
return () => window.removeEventListener("storage", callback)
}
//从localStorage中获取数据 如果读不到返回默认值
const getSnapshot = () => {
return (
(localStorage.getItem(key)
? JSON.parse(localStorage.getItem(key)!)
: null) || defaultValue
)
}
//修改数据
const setStorage = (value: any) => {
localStorage.setItem(key, JSON.stringify(value))
window.dispatchEvent(new StorageEvent("storage")) //手动触发storage事件
}
//返回数据
const res = useSyncExternalStore(subscribe, getSnapshot)
return [res, setStorage]
}
In App.tsx we can directly use the useStorage to achieve a simple counter. Values are stored in localStorage and are automatically updated when you refresh or change data from other tabs.
import { useStorage } from "./hooks/useStorage"
const App = () => {
const [val, setVal] = useStorage("data", 1)
return (
<>
<h3>{val}</h3>
<button onClick={() => setVal(val + 1)}>设置val</button>
</>
)
}
export default App
Effect Presentation
- Endurance of value: Click on the button to add val and keep the latest value after the page is refreshed.
- Sync across tabs: When multiple tabs open the application, any one tab changes val, other tabs are updated in real time and synchronized.
2. Subscriptions to Hastory to make the route jump
Achieves a simple useHistory Hook to retrieve browser url information + parameters
import { useSyncExternalStore } from "react"
export const useHistory = () => {
const subscribe = (callback: () => void) => {
window.addEventListener("popstate", callback)
window.addEventListener("hashchange", callback)
return () => {
window.removeEventListener("popstate", callback)
window.removeEventListener("hashchange", callback)
}
}
const getSnapshot = () => {
return window.location.href
}
const push = (path: string) => {
window.history.pushState(null, "", path)
window.dispatchEvent(new PopStateEvent("popstate"))
}
const replace = (path: string) => {
window.history.replaceState(null, "", path)
window.dispatchEvent(new PopStateEvent("popstate"))
}
const res = useSyncExternalStore(subscribe, getSnapshot)
return [res, push, replace] as const
}
Use History Hook
Let's use this useHistory Hook in the components to achieve basic forward, back-up and programmable navigation.
import { useHistory } from "./hooks/useHistory"
const App = () => {
const [history, push, replace] = useHistory()
return (
<>
<div>当前url:{history}</div>
<button
onClick={() => {
push("/aaa")
}}
>
跳转
</button>
<button
onClick={() => {
replace("/bbb")
}}
>
替换
</button>
</>
)
}
export default App
Effect Presentation
-
History: This is the current path value returned by the useHistory. The useSyncExternalStore automatically triggers an update to keep history up to date every time a URL changes.
-
Push and replace: Click on the "jump" button to call push ("/aaaa"), push /aaa into history; click on the "Replace" button to call on replace ("/bbb"), replace the current path with /bbb.
Attention
React renders the component if getSnapshot returns a value different from the previous one. That is why, if it always returns to a different value, it goes into an infinite cycle and produces this blunder.
Uncaught (in promise) Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
function getSnapshot() {
return myStore.todos //object
}
This writing returns the reference to the object, and React re-renders the component even if the object has not changed.
If your stocke data is variable, the getSnapshot function should return a non-variable snapshot of it. That means that there is a need to create new objects, but not every call. Instead, you should keep the snapshots obtained from the last calculation and return the same snapshots as the previous one when the data in the store remain unchanged. It depends on how you change the variable data.
function getSnapshot() {
if (myStore.todos !== lastTodos) {
// 只有在 todos 真的发生变化时,才更新快照
lastSnapshot = { todos: myStore.todos.slice() }
lastTodos = myStore.todos
}
return lastSnapshot
}
useTransition
useTransition is a Hook introduced in React 18 to manage transition situations in UI, especially when processing long run state updates. It allows you to mark certain updates as “transitional” so that React can prioritize more important updates, such as user input, while delaying the processing of transition updates.
Usage
const [isPending, startTransition] = useTransition()
Parameters
useTransition does not require any arguments
Return value
useTransition returns one array containing two elements
isPending(boolean) to tell you if there is a pending transfer.startTransition(function) function, you can use this method to mark status update as transfer.
Priority
Not important (general) because Less is applied in practice
Examples
We need a lot of simulations here, using mockjs simulations, the tools I use, beyond your imagination, the tools and plugins I used.
And we're going to get an api with a vite plugin that can help us simulate data.
npm install mockjs
mockjs document address: https://github.com/nuysoft/Mock/wiki/Getting-Started
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react-swc"
import type { Plugin } from "vite"
import mockjs from "mockjs"
import url from "node:url"
const viteMockServer = (): Plugin => {
return {
name: "vite-mock-server",
//使用vite插件的钩子函数
configureServer(server) {
server.middlewares.use("/api/list", async (req, res) => {
const parsedUrl = url.parse(req.originalUrl, true)
//获取url参数 true表示返回对象 {keyWord: 'xx'}
const query = parsedUrl.query
res.setHeader("Content-Type", "application/json")
const data = mockjs.mock({
//返回1000条数据
"list|1000": [
{
"id|+1": 1, //id自增
name: query.keyWord, //name为url参数中的keyWord
address: "@county(true)", //address为随机地址
},
],
})
//返回数据
res.end(JSON.stringify(data))
})
},
}
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), viteMockServer()],
})
Write access to our interface http://localhost:5174/api/list?keyWord=xx 5174 is the default port, which can be changed by itself and returns the data below

Frontend
Component Structure
In our example, we created a simple input box and a list to show results based on input keywords. The following are the main components of the components:
Input, Flex, List Source
antdhttps://ant.design/components/input/
npm install antd
import { useTransition, useState } from "react"
import { Input, Flex, List } from "antd"
interface Item {
id: number
name: string
address: string
}
const App = () => {
const [inputValue, setInputValue] = useState("")
const [isPending, startTransition] = useTransition() // 开始过渡
const [list, setList] = useState<Item[]>([])
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setInputValue(value)
fetch(`/api/list?keyWord=${value}`)
.then((res) => res.json())
.then((data) => {
const res = data?.list ?? []
// 使用过渡 useTransition
startTransition(() => {
setList([...res])
})
//不使用过渡 useTransition
//setList([...res])
})
}
return (
<>
<Flex>
<Input
value={inputValue}
onChange={handleInputChange} // 实时更新
placeholder="请输入姓名"
/>
</Flex>
{isPending && <div>loading...</div>}
<List
dataSource={list}
renderItem={(item) => (
<List.Item>
<List.Item.Meta title={item.name} description={item.address} />
</List.Item>
)}
/>
</>
)
}
export default App
- Input Box and Status Management Use the use State Hook to manage the list of values and results of the input box. The handleInputChange function is triggered every time the contents of the input box change, it takes the value entered by the user and performs the API request.
- API Request In handleInputChange, the value entered is sent as a query parameter to /api/ list API. API returns data to update the results list. To optimize the user experience, we have updated the results in the StartTransight function so that React can maintain the responsiveness of the input box when processing the update.
- Use useTransion UseTransion returns a boolean value is Pending to indicate whether the transition is still in progress. When the user enters, if the data is being loaded, we show a simple "loading" hint to inform the user that the current operation is still in progress.
- List render Displays the returned result using the List component, and the list entry shows the name and address of each result.
For better test results, you can downgrade the cpu retrospect speed.

Attention
StartTransion must be synchronized
Mispractice
startTransition(() => {
// ❌ 在调用 startTransition 后更新状态
setTimeout(() => {
setPage("/about")
}, 1000)
})
Correct approach
setTimeout(() => {
startTransition(() => {
// ✅ 在调用 startTransition 中更新状态
setPage("/about")
})
}, 1000)
async await
startTransition(async () => {
await someAsyncFunction()
// ❌ 在调用 startTransition 后更新状态
setPage("/about")
})
Correct approach
await someAsyncFunction()
startTransition(() => {
// ✅ 在调用 startTransition 中更新状态
setPage("/about")
})
Principle Parsing
The core principle of the useTransion is to treat some of the state updates as low-priority tasks, which allow for the implementation of key high-priority tasks first, while the transition updates at low-priority levels are slightly delayed. This is particularly effective in reproducing large amounts of data, in complex calculations or in processing long missions. React manages priorities through a dispatch mechanism:
- High-priority update: tasks that directly affect user experience, such as form input, button clicks, etc.
- Low-priority update: transition tasks that are relatively non-productive to interactive tasks, such as large data rendering, animation, etc., can be delayed.
+-----------------------+
| App |
| |
| +--------------+ |
| | Input | |
| +--------------+ |
| |
| +--------------+ |
| | Display | |
| +--------------+ |
+-----------------------+
用户输入
|
v
[高优先级更新] ---> [调度器] ---> [React 更新组件]
|
+---> [低优先级过渡更新] --> [调度器] --> [等待处理]
useDeferredValue
Use DeveredValue to delay some state updates until the main rendering is completed. This is very useful for the content of HF updates (e.g. input frames, scrolls, etc.) and can make UIs more fluid and avoid performance problems due to frequent updates.
Associated issues: difference between useTransion and useDeferredValue
Both useTransition and useDeferredValue involve late updates, but their focus and use are slightly different:
- The main focus of the useTranstion is
Transition. It allows developers to control the delayed update of an update and also provides transitional markers to enable developers to add transitional feedback. - The main focus of concern is
Single value. It allows you to mark a state-specific update as a low priority.
Usage
const deferredValue = useDeferredValue(value)
Parameters
- value: value deferred (supports any type)
Return value
- DeferredValue: Delayed update value, returning the same delay value as you provided during the initial rendering
Attention
When useDeferredValue receives a different value than before (comparison with object.is), it arranges for a rear re-rendering, in addition to the current rendering (it still uses the old value). This backstage re-relay can be interrupted, and if the value has a new update, React will start from the top. For example, if the user enters in the input box faster than the chart that receives the delayed value, the chart will only be re-inverted after the user has stopped entering.
Case: delayed search for data update
npm install mockjs antd
- Antd UI Component Library
- mockjs simulation data
The following example shows how to use useDeferredValue delayed processing of inputs to improve the search performance of large data.
import React, { useState, useTransition, useDeferredValue } from "react"
import { Input, List } from "antd"
import mockjs from "mockjs"
interface Item {
name: number
address: string
}
export const App = () => {
const [val, setVal] = useState("")
const [list] = useState<Item[]>(() => {
// 使用 Mock.js 生成模拟数据
return mockjs.mock({
"list|10000": [
{
"id|+1": 1,
name: "@natural",
address: "@county(true)",
},
],
}).list
})
const deferredQuery = useDeferredValue(val)
const isStale = deferredQuery !== val // 检查是否为延迟状态
const findItem = () => {
//过滤列表,仅在 deferredQuery 更新时触发
return list.filter((item) => item.name.toString().includes(deferredQuery))
}
return (
<div>
<Input value={val} onChange={(e) => setVal(e.target.value)} />
<List
style={{ opacity: isStale ? "0.2" : "1", transition: "all 1s" }}
renderItem={(item) => (
<List.Item>
<List.Item.Meta title={item.name} description={item.address} />
</List.Item>
)}
dataSource={findItem()}
></List>
</div>
)
}
export default App
Effects

When using the use DeferredValue, the search content in the input box does not immediately trigger the list filter to avoid frequent rendering. Enter a stop time (looks like a throttle) to automatically update the list to eligible data, ensuring a smoother interactive experience.
A trap.
useDeferredValueis not barrier-resistant, it takes a fixed delay, for example, one second before certain behaviors are processed, but the use of DeveredValue is not a fixed delay, it can be delayed depending on the user's equipment, and when the equipment is good, the delay is almost unconscious.
Side effects
useEffect
useEffect is the hook used in React to process Side effects. And useEffect also functions here as a life cycle function, before which you may use componentDidMount, componentDidUpdate and componentWillUnmount in class components to address these life cycle events.
What's a side effect function, what's a pure function?
** This issue is also frequently asked during interviews. **
Pure Functions
- Enter the decision output: The same input will always get the same output. This means that function behaviour is predictable.
- No side effects: Pure function
Do not modify external statusdoes not depend on external variability. Therefore, operations within a pure function do not affect external variables, files, databases, etc.
Example (pure function)
const add = (x: number, y: number) => x + y
add(1, 2) //3
Side Effect Functions
- A side effect function refers to functions that change the external state or depend on external variability while performing.
- It's less predictable, but the side effects are not necessarily bad.
- High-coupling functions rely heavily on external variable state.
- Operation Reference Type
- Operation local storage, for example
localStorage - Call external API, e.g.
fetchajax - Operation
DOM - Timer
let globalVariable = 0
function calculateDouble(number) {
globalVariable += 1 //修改函数外部环境变量
localStorage.setItem("globalVariable", globalVariable) //修改 localStorage
fetch(/*…*/).then((res) => {
//网络请求
//…
})
document.querySelector(".app").style.color = "red" //修改 DOM element
return number * 2
}
Example (side effects function)
//------------副作用函数--------------
let obj = { name: "小满" }
const changeObj = (obj) => {
obj.name = "大满"
return obj
}
//小满
changeObj(obj) //修改了外部变量属于副作用函数
//大满
//------------修改成纯函数--------------
//也就是不会改变外部传入的变量
let obj = { name: "小满" }
const changeObj = (obj) => {
const newObj = window.structuredClone(obj) //深拷贝
newObj.name = "大满"
return newObj
}
console.log(obj, "before") //obj 小满
let newobj = changeObj(obj)
console.log(obj, "after", newobj) //obj 小满 newobj 大满
After learning about side effects, we can begin to understand useEffect
UseEffect
useEffect(setup, dependencies?)
Parameters
-
Setup: Effect processing function returns a cleanup function. A component mounts with a setup, with a cleanup before a setup when relying on an update, and a cleanup when the component is unmounted.
-
List of response values (props, state, etc.) used in setup. It must be prepared in arrays such as [dep1, dep2]. Every time you do it, you do it.
Return value
UseEffect returns undefined
let a = useEffect(() => {})
console.log("a", a) //undefined
Basic use
A side effect function can do anything useEffect, such as operating DOM, network requests, timers, etc.
Operation Dom
import { useEffect } from "react"
function App() {
const dom = document.getElementById("data")
console.log(dom) //null
useEffect(() => {
const data = document.getElementById("data")
console.log(data) //<div id='data'>小满zs</div>
}, [])
return <div id="data">小满zs</div>
}
Network Request
useEffect(() => {
fetch("http://localhost:5174/?name=小满")
}, [])
Timing of implementation
Execute Component Mounting
Based on our following example, it can be observed that components perform useEffect side effects when mounted.
Similar to componentDidMount
useEffect(() => {
console.log("组件挂载时执行")
})
Execute on component update
- No dependent item update
Based on our following example, it can be observed that when there is a change in the response value, the side effect function useEffect is performed.
Similar to componentDidUpdate+ componentDidMount
import { useEffect, useState } from "react"
const App = () => {
const [count, setCount] = useState(0)
const [name, setName] = useState("")
useEffect(() => {
console.log("执行了", count, name)
})
return (
<div id="data">
<div>
<h3>count:{count}</h3>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
<div>
<h3>name:{name}</h3>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
</div>
)
}
export default App
- Other Organiser
Based on our following example, it can be observed that the side effects function of useEffect is performed when the count value in the dependent array changes. When the name value changes, it does not trigger the execution of the side effects function because it is not in the dependent array.
import { useEffect, useState } from "react"
const App = () => {
const [count, setCount] = useState(0)
const [name, setName] = useState("")
useEffect(() => {
console.log("执行了", count, name)
}, [count]) //当count发生改变时执行
return (
<div id="data">
<div>
<h3>count:{count}</h3>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
<div>
<h3>name:{name}</h3>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
</div>
)
}
export default App
- Reliance empty value
From the following example, it can be observed that when the dependent item is an empty array, the side effect function useEffect is performed only once, i.e. when the component is mounted.
Suitable for some Initialize operations, e.g., to get details or something.
import { useEffect, useState } from "react"
const App = () => {
const [count, setCount] = useState(0)
const [name, setName] = useState("")
useEffect(() => {
console.log("执行了", count, name)
}, []) //只会执行一次
return (
<div id="data">
<div>
<h3>count:{count}</h3>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
<div>
<h3>name:{name}</h3>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
</div>
)
}
export default App
Execute Component Unmounting
The side effect function useEffect returns a cleanup function, and the side effect function useEffect performs the cleanup function when the component is offloaded.
The cleanup function is exactly the side effect function of the previous time before the side effect function is run.
Based on our following example, it can be observed that when components are offloaded, the side effects function useEffect is performed.
Similar to componentWillUnmount
import { useEffect, useState } from "react"
// 子组件
const Child = (props: { name: string }) => {
useEffect(() => {
console.log("render", props.name)
// 返回一个清理函数
return () => {
console.log("unmount", props.name)
}
}, [props.name])
return <div>Child:{props.name}</div>
}
const App = () => {
const [show, setShow] = useState(true)
const [name, setName] = useState("")
return (
<div id="data">
<div>
<h3>父组件</h3>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={() => setShow(!show)}>显示/隐藏</button>
</div>
<hr />
<h3>子组件</h3>
{show && <Child name={name} />}
</div>
)
}
export default App
Clean Function Application
In our next example, for example, when name values change, the useEffect side effect function is executed and a timer is activated, and when name values change again, the useEffect side effect function is performed to clear the last timer. This avoids duplication of implementation of interface requests.
import { useEffect, useState } from "react"
// 子组件
const Child = (props: { name: string }) => {
useEffect(() => {
let timer = setTimeout(() => {
fetch(`http://localhost:5174/?name=${props.name}`)
}, 1000)
return () => {
clearTimeout(timer)
}
}, [props.name])
return <div>Child</div>
}
const App = () => {
const [show, setShow] = useState(true)
const [name, setName] = useState("")
return (
<div id="data">
<div>
<h3>父组件</h3>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={() => setShow(!show)}>显示/隐藏</button>
</div>
<hr />
<h3>子组件</h3>
{show && <Child name={name} />}
</div>
)
}
export default App
Real cases
The following is a case of real access to user information by id and new user information when id changes.
import React, { useState, useEffect } from "react"
interface UserData {
name: string
email: string
username: string
phone: string
website: string
}
function App() {
const [userId, setUserId] = useState(1) // 假设初始用户ID为1
const [userData, setUserData] = useState<UserData | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
const fetchUserData = async () => {
setLoading(true)
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
) //免费api接口 可以直接使用
if (!response.ok) {
throw new Error("网络响应不正常")
}
const data = await response.json()
setUserData(data)
} catch (err: any) {
setError(err.message)
} finally {
setLoading(false)
}
}
fetchUserData()
}, [userId])
const handleUserChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setUserId(parseInt(event.target.value))
}
return (
<div>
<h1>用户信息应用</h1>
<label>
输入用户ID:
<input
type="number"
value={userId}
onChange={handleUserChange}
min="1"
max="10"
/>
</label>
{loading && <p>加载中...</p>}
{error && <p>错误: {error}</p>}
{userData && (
<div>
<h2>用户信息</h2>
<p>姓名: {userData.name}</p>
<p>邮箱: {userData.email}</p>
<p>用户名: {userData.username}</p>
<p>电话: {userData.phone}</p>
<p>网站: {userData.website}</p>
</div>
)}
</div>
)
}
export default App

useLayoutEffect
useLayoutEffect is a Hook in React to trigger before the browser redraws the screen. Similar to the useEffect.
Usage
useLayoutEffect(() => {
// 副作用代码
return () => {
// 清理代码
}
}, [dependencies])
Parameters
-
Setup: Effect processing function returns a cleanup function. A component mounts with a setup, with a cleanup before a setup when relying on an update, and a cleanup when the component is unmounted.
-
List of response values (props, state, etc.) used in setup. It must be prepared in arrays such as [dep1, dep2]. Every time you do it, you do it.
Return value
Use LayoutEffect returns undefined
Differentiation (use LayoutEffect/useEffect)
| Difference | useLayoutEffect | useEffect |
|---|---|---|
| Timing of implementation | Browser completes layout and draws Before to perform side effects | Browser completes layout and draws After to perform side effects |
| Means of implementation | Sync execution | Step execution |
| Dom Render | Block Dom Rendering | Do not block Dom rendering |
Test DOM Block
The following example shows the difference between the use of LayoutEffect and the useEffect in Dom rendering. Use LayoutEffect will block Dom's rendering, and useEffect won't.
import React, { useLayoutEffect, useEffect, useState } from "react"
function App() {
const [count, setCount] = useState(0)
//不阻塞DOM
// useEffect(() => {
// for (let i = 0; i < 50000; i++) {
// //console.log(i);
// setCount(count => count + 1)
// }
// }, []);
//阻塞DOM
// useLayoutEffect(() => {
// for (let i = 0; i < 50000; i++) {
// //console.log(i);
// setCount(count => count + 1)
// }
// }, []);
return (
<div>
<div>app </div>
{Array.from({ length: count }).map((_, index) => (
<div key={index}>{index}</div>
))}
</div>
)
}
export default App
Test Synchronized Interstep Rendering
In the following animation example code:
-
UseEffect to achieve animated effects:
- Initial rendering
- Browser completes the drawing
- UseEffect Step execution, setting opacy: 1
- User can see the full faded animation transition effect
-
The animated effects of using LayoutEffect:
- Initial rendering
- Synchronize the useLayoutEffect as soon as DOM updates
- Set levels: 1
- Browser Draws in End state
- User does not see transition animation effects
#app1 {
width: 200px;
height: 200px;
background: red;
}
#app2 {
width: 200px;
height: 200px;
background: blue;
margin-top: 20px;
position: absolute;
top: 230px;
}
import React, { useLayoutEffect, useEffect, useRef } from "react"
function App() {
// 使用 useEffect 实现动画效果
useEffect(() => {
const app1 = document.getElementById("app1") as HTMLDivElement
app1.style.transition = "opacity 3s"
app1.style.opacity = "1"
}, [])
// 使用 useLayoutEffect 实现动画效果
useLayoutEffect(() => {
const app2 = document.getElementById("app2") as HTMLDivElement
app2.style.transition = "opacity 3s"
app2.style.opacity = "1"
}, [])
return (
<div>
<div id="app1" style={{ opacity: 0 }}>
app1
</div>
<div id="app2" style={{ opacity: 0 }}>
app2
</div>
</div>
)
}
export default App
Apply scene
- Need to read or change the DOM in sync: For example, you need to read the size or location of the element and adjust it before rendering.
- Prevention of scintillation: In some cases, the scrambling of a different utilisation may result in a visible layout. For example, animated start-up or some visible rapid DOM changes.
- Simulate the life-cycle approach: If you are moving old class components to functional components, you need to simulate the synchronous behaviour of the functional Did Mount, coponentDidUpdate and coponentWillUnmount.
Cases
You can record the scrollbar position when the user returns to this page and scrolls to the position previously recorded. Enhanced user experience.
import React, { useLayoutEffect, useRef } from "react"
function App() {
useLayoutEffect(() => {
const list = document.getElementById("list") as HTMLUListElement
list.scrollTop = 900
}, [])
return (
<ul id="list" style={{ height: "500px", overflowY: "scroll" }}>
{Array.from({ length: 500 }, (_, i) => (
<li key={i}>Item {i + 1}</li>
))}
</ul>
)
}
export default App
useInsertionEffect
Organisation
useRef
Use Ref when you need to process the DOM element in the React or you need to keep the persistence data between components.
import { useRef } from "react"
const refValue = useRef(initialValue)
refValue.current // 访问ref的值 类似于vue的ref,Vue的ref是.value,其次就是vue的ref是响应式的,而react的ref不是响应式的
Operate Dom elements through Ref
Parameters
- Initial Value: the initial value of the curent properties of the ref object. It can be any type of value. This parameter is ignored after the first rendering.
Return value
- Use Ref returns an object whose current attribute points to the initial value that is imported.
{current:xxxx}
Attention.
- React does not redo components when changing the ref.curent properties. React does not know when it will change because ref is an ordinary JavaScript object.
- Do not write or read ref.curent during rendering, except for initialization, which makes component behaviour unpredictable.
import { useRef } from "react"
function App() {
//首先,声明一个 初始值 为 null 的 ref 对象
let div = useRef(null)
const heandleClick = () => {
//当 React 创建 DOM 节点并将其渲染到屏幕时,React 将会把 DOM 节点设置为 ref 对象的 current 属性
console.log(div.current)
}
return (
<>
{/*然后将 ref 对象作为 ref 属性传递给想要操作的 DOM 节点的 JSX*/}
<div ref={div}>dom元素</div>
<button onClick={heandleClick}>获取dom元素</button>
</>
)
}
export default App
Data Storage
We achieve an example of new and old values that keep count, but in the process we find a problem, which is why the value of Num has been zero.
The value of the num has been zero since, after implementation of useState SetCount, the component will be rerendered and the value of the num will be initialized to zero.
import React, { useLayoutEffect, useRef, useState } from "react"
function App() {
let num = 0
let [count, setCount] = useState(0)
const handleClick = () => {
setCount(count + 1)
num = count
}
return (
<div>
<button onClick={handleClick}>增加</button>
<div>
{count}:{num}
</div>
</div>
)
}
export default App

How?
We can use the useref to solve this problem, because the useref will only be implemented once at the time of initialization, and the value of the useref will not be re-initiated when the component reRender is.
import React, { useLayoutEffect, useRef, useState } from "react"
function App() {
let num = useRef(0)
let [count, setCount] = useState(0)
const handleClick = () => {
setCount(count + 1)
num.current = count
}
return (
<div>
<button onClick={handleClick}>增加</button>
<div>
{count}:{num.current}
</div>
</div>
)
}
export default App

Practical application
We achieve an example of a timer, which is executed every 300 ms at the start of the click, and is cleared at the end of the click.
Problem
We found out that the timer wasn't cleared when we clicked on the end.
Reason
This is because the component has been re-rendering, so the value of the timmer has been re-entrusted to null, making it impossible to clear the timer.
import React, { useLayoutEffect, useRef, useState } from "react"
function App() {
console.log("render")
let timer: NodeJS.Timeout | null = null
let [count, setCount] = useState(0)
const handleClick = () => {
timer = setInterval(() => {
setCount((count) => count + 1)
}, 300)
}
const handleEnd = () => {
console.log(timer)
if (timer) {
clearInterval(timer)
timer = null
}
}
return (
<div>
<button onClick={handleClick}>开始计数</button>
<button onClick={handleEnd}>结束计数</button>
<div>{count}</div>
</div>
)
}
export default App
How?
We can use the useref to solve this problem, because the value of the useref will not be changed by the retrofitting of the components.
import React, { useLayoutEffect, useRef, useState } from "react"
function App() {
console.log("render")
let timer = useRef<null | NodeJS.Timeout>(null)
let [count, setCount] = useState(0)
const handleClick = () => {
timer.current = setInterval(() => {
setCount((count) => count + 1)
}, 300)
}
const handleEnd = () => {
if (timer.current) {
clearInterval(timer.current)
timer.current = null
}
}
return (
<div>
<button onClick={handleClick}>开始计数</button>
<button onClick={handleEnd}>结束计数</button>
<div>{count}</div>
</div>
)
}
export default App
Attention
-
The value of the component will not be re-introduced when re-reduced.
-
React does not redo components when changing the ref.curent properties. React does not know when it will change because ref is an ordinary JavaScript object.
-
The value of useref cannot be used as a dependency item for other things like useEffect, because it is not a reactive state.
-
Use Ref does not directly access examples of sub-components and needs to use ForwardRef.
useImperativeHandle
The parent component The handle. can be exposed inside the sub-component, so humans say that the parent component can call the method of the sub-component or access the properties of the sub-component.
If you learn Vue, it's like Vue's defineExpose.
Usage
useImperativeHandle(ref, () => {
return {
// 暴露给父组件的方法或属性
}
}, [deps])
Parameters
- ref: ref objects passed by parent component
- curatehandle: returns value, returns an object whose properties are the methods or properties by which sub-components are exposed to parent components
- Deps?: [optional] Dependencies are called back when the dependencies change, similar to
useEffectdependencies
Introduction cases
::: tip
Useref in 18 version different from 19 version
:::
Version 18
Version 18 needs to be used with forwardRef
After packing forwardref, there are two parameters, the first is props and the second is ref
All we need to do is pass the ref to useImperativeHandle and then useImperativeHandle can expose the method or attribute of the subcomponent to the parent component.
The parent component can then call the sub-component by ref or access the sub-component properties.
interface ChildRef {
name: string
count: number
addCount: () => void
subCount: () => void
}
//React18.2
const Child = forwardRef<ChildRef>((_, ref) => {
const [count, setCount] = useState(0)
//重点
useImperativeHandle(ref, () => {
return {
name: 'child',
count,
addCount: () => setCount(count + 1),
subCount: () => setCount(count - 1)
}
})
return <div>
<h3>我是子组件</h3>
<div>count:{count}</div>
<button onClick={() => setCount(count + 1)}>增加</button>
<button onClick={() => setCount(count - 1)}>减少</button>
</div>
})
function App() {
const childRef = useRef<ChildRef>(null)
const showRefInfo = () => {
console.log(childRef.current)
}
return (
<div>
<h2>我是父组件</h2>
<button onClick={showRefInfo}>获取子组件信息</button>
<button onClick={() => childRef.current?.addCount()}>操作子组件+1</button>
<button onClick={() => childRef.current?.subCount()}>操作子组件-1</button>
<hr />
<Child ref={childRef}></Child>
</div>
);
}
export default App;
Version 19
- 19 editions don't need to be used with
forwardRef, just use them. He'll put Ref and props together. You'll find it easier. - For 19 version useref the parameter must be passed into one parameter, e.g.
useRef<ChildRef>(null)
interface ChildRef {
name: string
count: number
addCount: () => void
subCount: () => void
}
//React19
const Child = forwardRef<ChildRef>((_, ref) => { // [!code --]
const Child = ({ ref }: { ref: React.Ref<ChildRef> }) => { // [!code ++]
const [count, setCount] = useState(0)
useImperativeHandle(ref, () => {
return {
name: 'child',
count,
addCount: () => setCount(count + 1),
subCount: () => setCount(count - 1)
}
})
return <div>
<h3>我是子组件</h3>
<div>count:{count}</div>
<button onClick={() => setCount(count + 1)}>增加</button>
<button onClick={() => setCount(count - 1)}>减少</button>
</div>
}
function App() {
const childRef = useRef<ChildRef>(null)
const showRefInfo = () => {
console.log(childRef.current)
}
return (
<div>
<h2>我是父组件</h2>
<button onClick={showRefInfo}>获取子组件信息</button>
<button onClick={() => childRef.current?.addCount()}>操作子组件+1</button>
<button onClick={() => childRef.current?.subCount()}>操作子组件-1</button>
<hr />
<Child ref={childRef}></Child>
</div>
);
}
export default App;
Timing of implementation [third parameter]
- If the third parameter is not entered,
useImperativeHandlewill be performed once when the component is mounted and then once when the status is updated
useImperativeHandle(ref, () => {})
- If a third parameter is entered and is an empty array,
useImperativeHandlewill be executed once the component is mounted and then not when the status is updated
useImperativeHandle(ref, () => {}, [])
- If the third parameter is entered and is of value,
useImperativeHandlewill be carried out once the component is mounted and will then decide whether to re-enforce depending on the changes in the dependencies
const [count, setCount] = useState(0)
useImperativeHandle(ref, () => {}, [count])
Actual cases
For example, we sealed a form component and provided two methods: validation and replacement. Use useImperativeHandle to expose these methods to the parent component, which can be called by ref.
interface ChildRef {
name: string
validate: () => string | true
reset: () => void
}
const Child = ({ ref }: { ref: React.Ref<ChildRef> }) => {
const [form, setForm] = useState({
username: '',
password: '',
email: ''
})
const validate = () => {
if (!form.username) {
return '用户名不能为空'
}
if (!form.password) {
return '密码不能为空'
}
if (!form.email) {
return '邮箱不能为空'
}
return true
}
const reset = () => {
setForm({
username: '',
password: '',
email: ''
})
}
useImperativeHandle(ref, () => {
return {
name: 'child',
validate: validate,
reset: reset
}
})
return <div style={{ marginTop: '20px' }}>
<h3>我是表单组件</h3>
<input value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} placeholder='请输入用户名' type="text" />
<input value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder='请输入密码' type="text" />
<input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder='请输入邮箱' type="text" />
</div>
}
function App() {
const childRef = useRef<ChildRef>(null)
const showRefInfo = () => {
console.log(childRef.current)
}
const submit = () => {
const res = childRef.current?.validate()
console.log(res)
}
return (
<div>
<h2>我是父组件</h2>
<button onClick={showRefInfo}>获取子组件信息</button>
<button onClick={() => submit()}>校验子组件</button>
<button onClick={() => childRef.current?.reset()}>重置</button>
<hr />
<Child ref={childRef}></Child>
</div>
);
}
export default App;
### useContext
useContext 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。设计的目的就是解决组件树间数据传递的问题。

### 用法
```ts
Rest MyThemeContext = React. CreateContext(theme: 'light'}); / / Create Man
function App () {
return (
<MyThemeContext.Provider value={{theme: 'light'}}>
<MyComponent />
</MyThemeContext.Provider>
)
}
function MyComponent() {
/ Use context
return (<div>{themeContext.theme}</div>);
}
Parameters
Participation
- Contact: is the object created by CreateContext, who does not keep information, he is the carrier of information. It was stated that it could be obtained from or provided to components.
Return value
- returns the value Context passed, and is read-only. React automatically re-renders the components of the context if the context changes
Basic use
::: info The following example passes a theme through context. This Hook is used differently in React 18 and React 19. :::
- 18 Version Presentation
First, we create a context through CreateContext, then deliver the value through the component packages created by CreateContext.
The packaged components, at any level, can be given the value of the context, and how can they be used?
The method used is to access the context through the useContext-book, which is then uploaded to the context.
import React, { useContext, useState } from "react"
/ / Create Context
const ThemeContext = React.createContext<ThemeContextType>(
{} as ThemeContextType
)
// Define Context Type
interface ThemeContextType {
theme: string
setTheme: (theme: string) => void
}
const Child = () => {
/ Get Context
const themeContext = useContext(ThemeContext)
const styles = {
backgroundColor: themeContext.theme === "light" ? "white" : "black",
border: "1px solid red",
width: 100 + "px",
height: 100 + "px",
color: themeContext.theme === "light" ? "black" : "white",
}
return (
<div>
<div style={styles}>child</div>
</div>
)
}
const Parent = () => {
/ Get Context
const themeContext = useContext(ThemeContext)
const styles = {
backgroundColor: themeContext.theme === "light" ? "white" : "black",
border: "1px solid red",
width: 100 + "px",
height: 100 + "px",
color: themeContext.theme === "light" ? "black" : "white",
}
return (
<div>
<div style={styles}>Parent</div>
<Child />
</div>
)
}
function App() {
const [theme, setTheme] = useState("light")
return (
<div>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Switch Theme
</button>
<ThemeContext.Provider value={{ theme, setTheme }}>
<Parent />
</ThemeContext.Provider>
</div>
)
}
export default App
- 19 Version Presentation
::: tip React 19 is similar to React 18, but it is simpler because you can use the context directly without wrapping components in a Provider. :::
import React, { useContext, useState } from 'react';
const ThemeContext = React.createContext<ThemeContextType>({} as ThemeContextType);
interface ThemeContextType {
theme: string;
setTheme: (theme: string) => void;
}
const Child = () => {
const themeContext = useContext(ThemeContext);
const styles = {
backgroundColor: themeContext.theme === 'light' ? 'white' : 'black',
border: '1px solid red',
width: 100 + 'px',
height: 100 + 'px',
color: themeContext.theme === 'light' ? 'black' : 'white'
}
return <div>
<div style={styles}>
child
</div>
</div>
}
const Parent = () => {
const themeContext = useContext(ThemeContext);
const styles = {
backgroundColor: themeContext.theme === 'light' ? 'white' : 'black',
border: '1px solid red',
width: 100 + 'px',
height: 100 + 'px',
color: themeContext.theme === 'light' ? 'black' : 'white'
}
return <div>
<div style={styles}>
Parent
</div>
<Child />
</div>
}
function App() {
const [theme, setTheme] = useState('light');
return (
<div>
{\bord0\shad0\alphaH3D}Toggle theme </button>
<ThemeContext.Provider value={{ theme, setTheme }}> // [!code --]
<ThemeContext value={{ theme, setTheme }}> // [!code ++]
<Parent />
</ThemeContext.Provider> // [!code --]
<ThemeContext> // [!code ++]
</div >
);
}
export default App;
Attention
- When using ThemeContext, the key must be
value
/ / n/ n/ n/ n: prop should be "value"
<ThemeContext theme={theme}>
<Button />
</ThemeContext>
/ / ✅ Pass value as prop
<ThemeContext value={theme}>
<Button />
</ThemeContext>
- Could use multiple Context
::: tip When using multiple contexts, take care not to reuse the same value in a way that causes one value to overwrite another. :::
const ThemeContext = React.createContext({ theme: "light" })
function App() {
return (
<ThemeContext value={{ theme: "light" }}>
<ThemeContext value={{ theme: "dark" }}>
{" "}
{/* Covers the above value */}
<Parent />
</ThemeContext>
</ThemeContext>
)
}
State birth.
useMemo
useMemo is a performance optimization provided by React. Its main function is to avoid complex calculations and object reconstruction at each rendering. By remembering the results of the last calculation, only recalculations were made when relying on changes in the item, improving performance, somewhat similar to computed for Vue.
React.memo
React.memo is a React API to optimize performance. By remembering the result of the previous rendering, it is re-rendered only when the props change, avoiding re-rendering.
Usage
Use React.memo package component [Generally for sub-components] to avoid re downscaling of components.
import React, { memo } from "react"
const MyComponent = React.memo(({ prop1, prop2 }) => {
/ Component Logic
})
const App = () => {
return <MyComponent prop1="value1" prop2="value2" />
}
React.memo case
First specify the conditions for react components to render:
- Props Changes in Component
- Change state of component
- UseContext Change
::: tip
Let's look at the following example, which does not use memo for caches, so each time the parent's state changes, the sub-components are recast.
And our sub-components only use usr information, but every time the parent component changes, the sub-components are retrofitted, so we use
memocaches. :::
import React, { useMemo, useState } from 'react';
interface User {
name: string;
age: number;
email: string;
}
interface CardProps {
user: User;
}
const Card = function ({ user }: CardProps) { // [!code --]
const Card = React.memo(function ({ user }: CardProps) { // [!code ++]
Console.log('Cardrender'); // / whenever the parent's state changes, the sub-components are re-reduced
const styles = {
backgroundColor: 'lightblue',
padding: '20px',
borderRadius: '10px',
margin: '10px'
}
return <div style={styles}>
<h1>{user.name}</h1>
<p>{user.age}</p>
<p>{user.email}</p>
</div>
} // [!code --]
}) // [!code ++]
function App() {
const [users, setUsers] = useState<User>({
Name: 'Chang San',
age: 18,
email: 'zhangsan@example.com'
});
const [search, setSearch] = useState('');
return (
<div>
<h1>Father Component</h1>
<input value={search} onChange={(e) => setSearch(e.target.value)} />
<Card user={users} />
</div>
);
}
export default App;
::: tip
When we use the memo cache, only if the user changes will the subcomponent be re-redressed, while the subcomponent is not re-redressed when the search changes.
:::
import React, { useMemo, useState } from "react"
interface User {
name: string
age: number
email: string
}
interface CardProps {
user: User
}
const Card = React.memo(function ({ user }: CardProps) {
console.log("Card render")
const styles = {
backgroundColor: "lightblue",
padding: "20px",
borderRadius: "10px",
margin: "10px",
}
return (
<div style={styles}>
<h1>{user.name}</h1>
<p>{user.age}</p>
<p>{user.email}</p>
</div>
)
})
function App() {
const [users, setUsers] = useState<User>({
Name: "Chang San",
age: 18,
email: "zhangsan@example.com",
})
const [search, setSearch] = useState("")
return (
<div>
<h1>Father Component</h1>
<input value={search} onChange={(e) => setSearch(e.target.value)} />
<div>
<button
onClick={() =>
setUsers({
Name: "Lee Four",
age: Math.random() * 100,
email: "lisi@example.com",
})
}
>
Update user
</button>
</div>
<Card user={users} />
</div>
)
}
export default App
React.memo Summary
-
Use scenario:
- When sub-components receive props that do not change frequently
- When the re-rendering component costs more money
- When needing to avoid unnecessary rendering
-
** Advantages**
- Avoid unnecessary retrospect through memory
- Improved application performance
- Reduction in resource consumption
-
Note:
- Do not overuse, only on components that do require optimization
- For simple components, using
memomay cost more than replicating - If props changes frequently, the effect of
memowill be significantly reduced
Use Memo Usage
import React, { useMemo, useState } from "react"
const App = () => {
const [count, setCount] = useState(0)
const memoizedValue = useMemo(() => count, [count])
return <div>{memoizedValue}</div>
}
Parameters
Participation
- Backup function: Funaction: returns the value for which cache is required
- Dependency item: Array: The echo function re-executs
The timing of execution is similar to that of the use of Effect.when the dependencies change
Return value
- Return value: return value
It's not a function after returning.that requires cache
UseMemo Case
::: tip
Let us look at the following example, which does not use useMemo for a cache, so every time a search changes, total is recalculated, which leads to unnecessary calculations, so we can use useMemo caches, because our total has nothing to do with search, so if the logic of the calculation is more complex, then it creates performance problems.
:::
import React, { useMemo, useState } from "react"
function App() {
const [search, setSearch] = useState("")
const [goods, setGoods] = useState([
id: 1, name: Apple, price: 10, count: 1,
id: 2, name: "Banana", price: 20, count: 1,
id: 3, name: Orange, price: 30, count: 1,
])
const handleAdd = (id: number) => {
setGoods(
goods.map((item) =>
item.id === id ? { ...item, count: item.count + 1 } : item
)
)
}
const handleSub = (id: number) => {
setGoods(
goods.map((item) =>
item.id === id ? { ...item, count: item.count - 1 } : item
)
)
}
const total = () => {
console.log("total")
// e.g. very complex calculation logic
return goods.reduce((total, item) => total + item.price * item.count, 0)
}
return (
<div>
<h1>Father Component</h1>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<table border={1} cellPadding={5} cellSpacing={0}>
<thead>
<tr>
Trade name <th> </th>
Commodity prices <th>
<th> Commodity Volume </th>
</tr>
</thead>
<tbody>
{goods.map((item) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.price * item.count}</td>
<td>
<button onClick={() => handleAdd(item.id)}>+</button>
<span>{item.count}</span>
<button onClick={() => handleSub(item.id)}>-</button>
</td>
</tr>
))}
</tbody>
</table>
Total price: {tinal()}</h2>
</div>
)
}
export default App
::: tip
When we use the useMemo Cache, we recalculate total only when the goods change, and total when the search changes.
:::
import React, { useMemo, useState } from "react"
function App() {
const [search, setSearch] = useState("")
const [goods, setGoods] = useState([
id: 1, name: Apple, price: 10, count: 1,
id: 2, name: "Banana", price: 20, count: 1,
id: 3, name: Orange, price: 30, count: 1,
])
const handleAdd = (id: number) => {
setGoods(
goods.map((item) =>
item.id === id ? { ...item, count: item.count + 1 } : item
)
)
}
const handleSub = (id: number) => {
setGoods(
goods.map((item) =>
item.id === id ? { ...item, count: item.count - 1 } : item
)
)
}
const total = useMemo(() => {
console.log("total")
return goods.reduce((total, item) => total + item.price * item.count, 0)
}, [goods])
return (
<div>
<h1>Father Component</h1>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<table border={1} cellPadding={5} cellSpacing={0}>
<thead>
<tr>
Trade name <th> </th>
Commodity prices <th>
<th> Commodity Volume </th>
</tr>
</thead>
<tbody>
{goods.map((item) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.price * item.count}</td>
<td>
<button onClick={() => handleAdd(item.id)}>+</button>
<span>{item.count}</span>
<button onClick={() => handleSub(item.id)}>-</button>
</td>
</tr>
))}
</tbody>
</table>
Total price: </h2>
</div>
)
}
export default App
UseMemo execution time (dependent entry)
- If the dependency is an empty array, the
useMemocallback function will be executed once - Specifies the dependencies, the
useMemocallback function is executed when the dependencies change - No dependencies specified, not recommended because they are executed every rendering and update
UseMemo Summary
-
Use scenario:
- When complex calculations need to cache
- When unnecessary recalculations need to be avoided
- When computing logic is complex and time-consuming
-
** Advantages**
- Avoiding unnecessary recalculations through memory
- Improved application performance
- Reduction in resource consumption
-
Note:
- Do not overuse, only on components that do require optimization
- If the dependencies change frequently, the use of Memo will be compromised.
- If the calculation logic is simple, the cost of using the use Memo may be greater than the recalculation
useCallback
Use Callback to optimize performance by returning a memory return function that reduces unnecessary retrofitting, that is, it is a function used in a cache component and avoids re-creation of a function.
Why do you need to use Callback?
In React, the retrosizing of a function component leads to the re-created function within the component, which may cause performance problems. UseCallback to reduce unnecessary retrofitting and improve performance through a cache function.
Usage
const memoizedCallback = useCallback(() => {
doSomething(a, b)
}, [a, b])
Parameters
Participation
- Callback function
- deps: relying on an array of items, when the dependencies change, the echo function is recreated, as is the useEffect.
Return value
- Returns a memory return function that reduces the number of functions created and enhances performance.
Case 1
Look at this example:
- We created a WeakMap to store the callback function and to record the number of times it was created.
- When components are re-rendered, the ChangeSearch function will be recreated and will be validated here. If the function is re-created, the number will be +1 and, if not, the number will be by default 1.
import { useCallback, useState } from "react"
const functionMap = new WeakMap()
let counter = 1
const App: React.FC = () => {
console.log("Render App")
const [search, setSearch] = useState("")
const changeSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value)
}
if (!functionMap.has(changeSearch)) {
functionMap.set(changeSearch, counter++)
}
Console.log("Function Id", FactionMap.get(changeSearch))
return (
<>
<input type="text" value={search} onChange={changeSearch} />
</>
)
}
export default App
When we change the value of the input box, we can see that the function Id is increasing, indicating that the function has been recreated.

Why is it 4 because the default is 1 and then the input box is changed three times, so it's 4? We use the useCallback to optimize.
:::tip
Wrap changeSearch with useCallback to keep its function reference stable and avoid unnecessary work.
:::
const changeSearch = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value)
}, [])
We can see that function Id has not been added, that the function has not been recreated.

Case 2
For sub-components:
- We created a Child sub-component and optimized it using React.memo, which, as mentioned in the previous chapter, will test whether props have changed and, if they have changed, redo the dye sub-component.
- We created a ChildCallback function that passed to sub-components, and then we entered box changes, and we found that sub-components were reprogramming, but we didn't change props.
- This is because the value of the input box changes and the App is re-reduced, and then the ChildCallback function is re-created and passed on to the sub-component, which will judge whether the function has changed, but each created function has a different memory address, so the sub-component is re-reduced.
import React, { useCallback, useState } from "react"
const Child = React.memo(
({
user,
callback,
}: {
user: { name: string; age: number }
callback: () => void
}) => {
console.log("Render Child")
const styles = {
color: "red",
fontSize: "20px",
}
return (
<div style={styles}>
<div>{user.name}</div>
<div>{user.age}</div>
<button onClick={callback}>callback</button>
</div>
)
}
)
const App: React.FC = () => {
const [search, setSearch] = useState("")
const [user, setUser] = useState({
name: "John",
age: 20,
})
const childCallback = () => {
Console.log
}
return (
<>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<Child callback={childCallback} user={user} />
</>
)
}
export default App
The ChildCallback function is recreated because it is re-reduced, and then passed to the sub-component, which will judge whether the function has changed, but each created function has a different memory address, so the sub-component will re-render.

:::tip
Wrap childCallback with useCallback so the memoized child does not re-render because of a new function reference.
:::
const childCallback = useCallback(() => {
Console.log
}, [])
Summary
The use of the Callback would need to be measured and not blindly applied to each method, which could lead to unnecessary performance losses. The use of Callback itself requires a certain amount of performance.
The useCallback is not intended to prevent a function from being re-created, but rather to rely on an entry to decide whether to return a new function or an old function, thus ensuring that the address of the function remains the same if the entry remains.
Tools
useDebugValue
useDebugValue is a React Hook designed for developers to debug custom Hook. This allows you to add a custom debug value to the React Developer tool for custom Hook.
Usage
const debugValue = useDebugValue(value)
Parameter Description
Participation
value: values to be displayed in React DevToolsformatter?: (optional) Format function- Role: Display format for custom values
- Call Time: Call only when React DevTools is open, with complex formatting operations
- Parameter: Receive value as parameter
- Returns: returns the displayed value after formatting
Return value
- No return value (void)
React DevTools
Mode I: Chrome Shop Installation
- Visit React Developer Tools
- Click "Add to Cropme" to install
Mode 2: Offline installation
- Get installation back to
React/React toolon Twitter public (Minami.) Package

:::info offline installation steps
- Opens the Chrome Browser, clicking on three dots in the top right corner → More tools → Extension
- Turn on the "developmenter mode" on the top right corner.
- Drag downloaded .crx files directly to the extension Page Noodles.
- Click Add Extension in the popup confirmation box :::
Field cases: custom use Cookie Hook
The practical application of useDebugValue is shown below by achieving a useCookie Hook. This Hook provides a full cookie operation and emphasizes the trial experience by useDebugValue.
import React, { useState, useDebugValue } from "react"
const useCookie = (name: string, initialValue: string = "") => {
const getCookie = () => {
const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]*)(;|$)`))
return match ? match[2] : initialValue
}
const [cookie, setCookie] = useState(getCookie())
const updateCookie = (value: string, options?: any) => {
document.cookie = `${name}=${value};${options}`
setCookie(value)
}
const deleteCookie = () => {
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`
setCookie(initialValue)
}
useDebugValue(cookie, (value) => {
return `cookie: ${value}`
})
return [cookie, updateCookie, deleteCookie] as const
}
const App: React.FC = () => {
const [cookie, updateCookie, deleteCookie] = useCookie("key", "value")
return (
<div>
<div>{cookie}</div>
<button
onClick={() => {
updateCookie("update-value")
}}
>
Set Cookie
</button>
<button
onClick={() => {
deleteCookie()
}}
>
Delete Cookie
</button>
</div>
)
}
export default App
Hook functional description
- getCookie: Get the cookies value of the given name
- updateCookie: Update or create a new cookie
- deleteCookie: Deletes specifiedcookie
Use DebugValue application
In this example, we use useDebugValue to show the value of the current cookie:
useDebugValue(cookie, (value) => `cookie: ${value}`)
Debug Effects Presentation
Display effects in React DevTools:

Show effects after updating cookies:

Use recommendations
- Use only
useDebugValuefor custom Hook - For simple values, formatter functions can be omitted
- When the calculation of formatted values is more expensive, it is recommended to use the formatter function because it will only be executed when the developer tool opens
useId
UseId is a new Hook added by React 18 to generate a stable unique identifier, which is used to resolve the ID inconsistencies in the SSR scene, or to generate a unique ID scene for the component.
Use scene
- Generate unique IDs for components
- Solve ID inconsistencies in the SSR scene
- Unique ID for accessibility interaction
Usage
const id = useId()
/ Return value: :r0: multi-call value increment
Parameter Description
Participation
- No entry
Return value
- Only identifier, e.g.
:r0:
Cases
1. Generate unique IDs for components
For example, tabel needs to bind to input, it is very convenient to use id properties to generate only ID manually and use use Id to automatically generate only ID.
export const App = () => {
const id = useId()
return (
<>
<label htmlFor={id}>Name</label>
<input id={id} type="text" />
</>
)
}
2. Resolution of ID inconsistencies in the SSR scene
Under the service render (SSR) scenario, the components are rendered on the service side and on the client side, respectively. The use of randomly generated IDs may result in inconsistent renderings and cause hydration errors. Use Id to ensure the generation of definitive IDs.
// A common SSR scene: a navigation column component with tooltips
const NavItem = ({ text, tooltip }) => {
/ / / Wrong practice: use random value or incremental value
const randomId = `tooltip-${Math.random()}`
/ / Service may generate tooltip-0.123 at SSR
// Potential to generate tooltip-0.456 on client
/ / Cause hydration mismatch
return (
<li>
<a aria-describedby={randomId} href="#">
{text}
</a>
<div id={randomId} role="tooltip">
{tooltip}
</div>
</li>
)
}
/ / ✅ Correct practice: use Id
const NavItemWithId = ({ text, tooltip }) => {
const id = useId()
const tooltipId = `${id}-tooltip`
return (
<li>
<a href="#" aria-describedby={tooltipId} className="nav-link">
{text}
</a>
<div id={tooltipId} role="tooltip" className="tooltip">
{tooltip}
</div>
</li>
)
}
/ / Use Example
const Navigation = () => {
return (
<nav>
<ul>
<NavItemWithId text="Home" tooltip="Return to the home page" />
<NavItemWithId text="Settings" tooltip="System settings" />
<NavItemWithId text="Profile" tooltip="View personal information" />
</ul>
</nav>
)
}
3. Accessibility interactive unique ID
aria-describedby is an ARIA attribute that provides additional descriptive text for elements. It links the description by referencing IDs of other elements and helps screen readers to provide more detailed information for users.
When users with visual impairment view the web page using a screen reader:
- When you read the input box, you will read the label of the input box first
- Then you can read the description text by
aria-describedby - The user will know what this input box needs to enter and what it requires.
export const App = () => {
const id = useId()
return (
<div>
<input type="text" aria-describedby={id} />
<p id={id}>
{" "}
Please enter a valid e-mail address, e.g. xiaoman@example.com
</p>
</div>
)
}
Summary
Basic introduction
UseId is the new Hook introduced by React 18 to generate a stable and unique identifier Symbol
Usage characteristics
- No input parameters required
- returns the only string of certainty (e. g.
:r0:) - Multiple calls from the same component generate an incremental ID
- Suitable for use in an id-stable scenario, not for visual or style purposes
Best practices
- Use the same useId call when more than one relevant ID is required and add suffix
- Do not use key properties for list rendering
- Priority for accessibility and SSR scenes
Other
Custom Hooks
We have already introduced the books (useState, useEffect, useContext, useReducer, useRef, useMemo, useCallback, useLayoutEffect, useImperativeHandle, useDebugValue, etc.) in React in the previous chapters, and then we'll talk about how to customize them.
Why do you need to custom-defined books?
Because, in practical development, React's built-in hooks do not meet all our needs, such as some complex business logic or some use scenes that require us to use custom hooks ourselves.
Customised Hooks Rules
- Custom Hooks must be
useHead - Custom Hooks can call other books (inline and custom)
Cases
For example, we need to make a watermark, a demand that is common in our business, for which we seal a self-defined hooks to fulfil it.
- First we define a configuration for a watermark.
import { useEffect, useState } from "react"
export interface WatermarkOptions {
Contact: string// watermark text
Width?: number// watermark width
Height?
FontSize?: number// watermark font size
fontColor?: string// watermark font colour
zIndex?: number// watermark level
Other Organiser degrees
gapX?: number// watermark horizontal spacing
Gappy?: number / / watermark vertical spacing
}
- Then we define the default value for the watermark.
const defaultOptions = (): Partial<WatermarkOptions> => {
/ Default to fill the entire page
const { width, height } = document.documentElement.getBoundingClientRect()
return {
width: width,
height: height,
fontSize: 16,
fontColor: "black",
zIndex: 9999,
rotate: -30,
gapX: 200,
gapY: 100,
}
}
- The whole line of thinking, how do we achieve it first by
canvas, by setting the attributes of the canvas, bytoDataURL, and then bytoDataURL, by generating a watermark picture, then creating an element, setting the watermark picture as a background image of the element, and setting the style, and if we are to operate the DOM element, we need to operate by using the Effect side effect function.
import { useEffect, useState } from "react"
export interface WatermarkOptions {
Contact: string// watermark text
Width?: number// watermark width
Height?
FontSize?: number// watermark font size
fontColor?: string// watermark font colour
zIndex?: number// watermark level
Other Organiser degrees
gapX?: number// watermark horizontal spacing
Gappy?: number / / watermark vertical spacing
}
/ Default Configuration
const defaultOptions = (): Partial<WatermarkOptions> => {
const { width, height } = document.documentElement.getBoundingClientRect()
return {
width: width,
height: height,
fontSize: 16,
fontColor: "black",
zIndex: 9999,
rotate: -30,
gapX: 200,
gapY: 100,
}
}
export const useWatermark = (options: WatermarkOptions) => {
const [watermarkOptions, setWatermarkOptions] =
useState<WatermarkOptions>(options)
const opts = Object.assign({}, defaultOptions(), watermarkOptions)
const updateWatermark = (newOptions: Partial<WatermarkOptions>) => {
setWatermarkOptions((prev) => ({
...prev,
...newOptions,
}))
}
useEffect(() => {
const canvas = document.createElement("canvas")
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D
canvas.width = opts.gapX!
canvas.height = opts.gapY!
/ Default
ctx.translate(opts.gapX! / 2, opts.gapY! / 2)
ctx.rotate((opts.rotate! * Math.PI) / 180)
ctx.font = `${opts.fontSize}px sans-serif`
ctx.textAlign = "center"
ctx.fillStyle = opts.fontColor!
ctx.globalAlpha = 0.15
ctx.fillText(opts.content, 0, 0)
const watermarkDiv = document.createElement("div")
watermarkDiv.id = "watermark"
watermarkDiv.style.position = "fixed"
watermarkDiv.style.top = "0"
watermarkDiv.style.left = "0"
watermarkDiv.style.width = `${opts.width}px`
watermarkDiv.style.height = `${opts.height}px`
watermarkDiv.style.pointerEvents = "none"
watermarkDiv.style.zIndex = `${opts.zIndex}`
watermarkDiv.style.overflow = "hidden"
watermarkDiv.style.backgroundImage = `url(${canvas.toDataURL()})`
watermarkDiv.style.backgroundSize = `${opts.gapX}px ${opts.gapY}px`
document.body.appendChild(watermarkDiv)
return () => {
document.body.removeChild(watermarkDiv)
}
}, [opts])
return [updateWatermark, opts] as const
}
- Code Details
ctx.translate(opts.gapX! / 2, opts.gapY! / 2)
ctx.rotate((opts.rotate! * Math.PI) / 180)
ctx.font = `${opts.fontSize}px sans-serif`
ctx.textAlign = "center"
ctx.fillStyle = opts.fontColor!
ctx.globalAlpha = 0.15
ctx.fillText(opts.content, 0, 0)
Now, you know, you're probably a little bit confused about this one, and we're going to explain it in detail here, first of all, by gapX, gapY, we've set the width for Canvas, the default is 200,100, which is a rectangular of 200px*100px, but the default coordinates of Canvas are (0,0), which will lead to text not being shown, so we move the text to the center, so what about the center? It is the width height/2, even out of the centre, and then move the text to the centre by ctx.translate(opts.gapX! / 2, opts.gapY! / 2).
The text is then rotated by ctx.rotate((opts.rotate! * Math.PI) / 180), and then the text is drawn by ctx.font = ${opts.fontSize}px sans-serif ``, set the font, then byctx.textAlign = 'center', set the text alignment, then byctx.fillStyle = optColor!, set the text colour, then pass`ctx.globalAlpha =0.15<xxctx.fillText(opts.content, 0, 0) ' .

- Use in component
import React from "react"
import { useWatermark } from "./hooks/useWatermark"
const App: React.FC = () => {
const [updateWatermark, opts] = useWatermark({
And I'm going to tell you something.
Watermark
const update = () => {
updateWatermark({
"Renew the watermark,"
})
}
return (
<>
<div>{JSON.stringify(opts)}</div>
Update watermarks </button>
</>
)
}
export default App

So, at work, do we need frequent definitions of books?
We do not need to repeat wheels, and there are already many ready-made banks that can be used, such as ahooks, react-use, SWR, react-hook-form and so on, which are validated by the community and can be used in a safe manner.
Use the "hooks" example here
Install hoooks

Document address: https://ahooks.js.org/zh-CN/hooks/use-request/index
npm install --save ahooks
## or
yarn add ahooks
## or
pnpm add ahooks
## or
bun add ahooks
Case 1:useMount component first retrospect
import React from "react"
import { useMount } from "ahooks"
const App: React.FC = () => {
useMount(() => {
console.log("mounted")
})
return (
<>
<div></div>
</>
)
}
export default App
Case 2: useRequest request
UseRequest is a very powerful HOOK in the hoooks that can be used to handle requests such as automatic/ manual requests, rotations, tremors, thrashing, screen focus re-requests, bugs retrying, loating delay, SWR (stable-wire-revalidate), caches, etc.
import React from "react"
import { useMount, useRequest } from "ahooks"
const App: React.FC = () => {
const { data, run } = useRequest(
() => {
return fetch("https://api.github.com/users/github").then((res) =>
res.json()
)
},
{
DebounceWait: 300, / / Wrightened
Manual: true, / / Manual trigger
}
)
return (
<>
<div>{JSON.stringify(data)}</div>
<button onClick={run}>Request </button>
</>
)
}
export default App
:::tip See the official documentation for other useful Hooks not covered here. :::
Router
Basic use
React-Router V7

React-router is the path bank of React, and if you learn Vue, it's very similar to the Router of Vue. Its function is to match different components according to URL and then render them. This allows you to jump into a single page application.
Official document: https://reactrouter.com/home
Install
React-router designed three models in its latest version V7
- Frame Mode
The frame mode is used, and the scaffolder template provided by React-Router is installed, and when installed, it will lead the route.
npx Create-react-router@latest my-react-router-app#
cd my-react-router-app
npm i # Installation Dependence
npm run dev# Start project
- Data Mode
The data pattern is that we can use our own templates to create React items, such as vite``webpack etc., and then install React-router.
#V7 is not required
export const router = createBrowserRouter([
{
path: "/",
Component: Home,
},
{
path: "/about",
Component: About,
},
])
- Declaration Mode
Declaration mode can also create React items with your own template and then install React-router yourself.
#V7 is not required
import React from "react"
import ReactDOM from "react-dom/client"
import { BrowserRouter, Routes, Route } from "react-router"
import App from "./app"
import About from "../about"
const root = document.getElementById("root")
ReactDOM.createRoot(root).render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="about" element={<About />} />
</Routes>
</BrowserRouter>
)
::: tip
The difference between the data mode and the statement mode allows the data model to use all React-router functions, including data processing. The mode of declaration can only be used as part of the function of React-router, such as the route jump.
Declaration Mode for a small project and Data Mode for an enterprise project.
:::
Basic use
- src/router/index.ts
Pages directory creates two components, Home and About
New directory router, add a new file index.ts to the directory, insert React-router in the document and then use createBrowserRouter to create a route.
import { createBrowserRouter } from "react-router"
import Home from "../pages/Home"
import About from "../pages/About"
const router = createBrowserRouter([
{
path: "/",
Component: Home,
},
{
path: "/about",
Component: About,
},
])
export default router
- src/App.tsx
Include route in App.tsx file and then use RouterProvider package App component.
import React from "react"
import { RouterProvider } from "react-router"
import router from "./router"
const App: React.FC = () => {
return (
<>
<RouterProvider router={router} />
</>
)
}
export default App
Route jump
In Home component, use NavLink component to jump to About component.
import { NavLink } from "react-router"
const Home: React.FC = () => {
return (
<div>
<NavLink to="/about">About</NavLink>
</div>
)
}
export default Home
In About component, use Link component to jump to Home component.
import { NavLink } from "react-router"
const About: React.FC = () => {
return (
<div>
<NavLink to="/">Home</NavLink>
</div>
)
}
export default About
Route Mode
In React RouterV7, there is a different mode of route, and the choice of route mode will directly affect your entire project. React Router provides four core path creation functions:
createBrowserRouter, createHashRouter, createMemoryRouter and createStaticRouter
1. Create Browner Router (recommended)
Core features:
- Hesterory API for HTML5 (pushstate, placestate, popstate)
- Browser URL is more pure (/search, /about, /user/123)
- Server-side support (nginx, apace, etc.) is required or will be refreshed 404
Use scene:
- Most modern browser environments
- Server support required
- Needs URL beauty
2. createHashRouter
Core features:
- Use the rash section of the URL (#/search, #/about, #/user/123)
- No server support required
- Refresh page does not lose
Use scene:
- Static site hosting e.g. (gethub pages, netlifty, vercel)
- No server support required
3. createMemoryRouter
Core features:
- Use RAM pathsheet
- Refresh page loses status
- Toggle display of URLs for page routers
Use scene:
- (React Nature, Electron)
- Unit Test or Component Test (Jest, Vitast)
4. createStaticRouter
Core features:
- Designed for Service Rendering (SSR)
- Match requested paths on the server side to generate static HTML
- Need to work with client routers (e.g. CreateBrowserRouter)
Use scene:
- Service rendering application (e. g. Next.js compatible)
- Pages requiring SEO optimization
Solve the issue of updating 404
When createBrowserRouter is used, the status is lost if the page is refreshed, because the browser defaults to request resources on the server and returns 404 if there are no resources on the server.
To solve this, configure a fallback route on the server so that requests for missing resources return index.html.

- Nginx (Recommended)
Download address: Nginx
location / {
try_files $uri $uri/ /index.html;
}

- Apache
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
- Vercel
{
"rewrites": [{ "source": "/:path*", "destination": "/index.html" }]
}
- Nodejs
const http = require("http")
const fs = require("fs")
const httpPort = 80
http
.createServer((req, res) => {
fs.readFile("index.html", "utf-8", (err, content) => {
if (err) {
console.log('We cannot open "index.html" file.')
}
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
})
res.end(content)
})
})
.listen(httpPort, () => {
console.log("Server listening on: http://localhost:%s", httpPort)
})
Route
React-Router V7 has a very wide variety of routes, with Embedded Routes Layout routers Index path Prefix route Dynamic route, broadly divided into these five categories, as described below.
Layout
We're going to do a layout of the interface before we can demonstrate some of the above routes, so we can follow up with the UI component.
npm install antd
npm install @ant-design/icons
We create a folder layout, a folder Content Header Menu in the folder and a document index.tsx in the folder, which reads as follows:
- src/layout/Menu/index.tsx
Menu Page
import { Menu as AntdMenu } from "antd"
import { AppstoreOutlined } from "@ant-design/icons"
import type { MenuProps } from "antd"
import { useNavigate } from "react-router"
export default function Menu() {
Const navigate = use navigate() // encoded navigation
const handleClick: MenuProps["onClick"] = (info) => {
Navigate (info.key)/ / Click on menu items to the corresponding page
}
const menuItems = [
{
key: "/home",
label: "Home",
icon: <AppstoreOutlined />,
},
{
key: "/about",
label: "About",
icon: <AppstoreOutlined />,
},
]
return (
<AntdMenu
onClick={handleClick}
style={{ height: "100vh" }}
items={menuItems}
/>
)
}
- src/layout/Header/index.tsx
Head Page
import { Breadcrumb } from "antd"
export default function Header() {
return (
<Breadcrumb
items={[
{
title: "Home",
},
{
title: "List",
},
{
title: "App",
},
]}
/>
)
}
- src/layout/Content/index.tsx
Content Page
import { Outlet } from "react-router"
export default function Content() {
return <Outlet />
}
- src/layout/index.tsx
Layout page becomes serialized
import Header from "./Header"
import Menu from "./Menu"
import Content from "./Content"
import { Layout as AntdLayout } from "antd"
export default function Layout() {
return (
<AntdLayout>
<AntdLayout.Sider>
<Menu />
</AntdLayout.Sider>
<AntdLayout>
<Header />
<AntdLayout.Content>
<Content />
</AntdLayout.Content>
</AntdLayout>
</AntdLayout>
)
}

Embedded Routes
Embedded routing is the , and the , which can inherit the routing of the parent routing or have its own layout.
Note:
- The father's path path begins at
index, so you need to add the father's path path to/index/home/index/about - Sub-routines don't need to add
/a path that writes directly. - The sub-routine default is not shown and the parent route is required to display the sub-routine outlet by
Outletcomponent is a container<router-view>displaying the sub-routing similar to Vue - Subroutine levels can be infinity, but it's two to three in general practice.
const router = createBrowserRouter([
{
path: "/index",
Component: Layout, / / Father route
children: [
// [!code highlight]
{
path: "home",
Component: Home, / / Subroutine
},
{
path: "about",
Component: About, / / Subroutine
},
],
},
])
import { Outlet } from "react-router"
function Content() {
return <Outlet />
}
Layout routers
The layout route is a special embedded route and the parent route is omitted path so that no additional path segment is added to the URL:
const router = createBrowserRouter([
{
/ path: '/index', / / omitted /[! code highlight]
Component: Layout,
children: [
{
path: "home",
Component: Home,
},
{
path: "about",
Component: About,
},
],
},
])
Index path
Index path is defined by index: true as the default subrouting of the parent route:
{ index: true, Component: Home }
Index path is shown in the parent URL of the parent 's URL
const router = createBrowserRouter([
{
path: "/",
Component: Layout,
children: [
{
index: true, // [!code highlight]
// path: 'home',
Component: Home,
},
{
path: "about",
Component: About,
},
],
},
])
Prefix route
The prefix is only set path instead of Component to add a single prefix to a group of routers:
const router = createBrowserRouter([
{
path: "/project",
/Commonent: Layout, / / omitted /[!code highlight]
children: [
{
path: "home",
Component: Home,
},
{
path: "about",
Component: About,
},
],
},
])
Dynamic route
Dynamic pathways define dynamic segments by : Parameter Name syntax:
Access rules are as follows: http://localhost:3000/home/123
const router = createBrowserRouter([
{
path: "/",
Component: Layout,
children: [
{
path: "home/:id", // [!code highlight]
Component: Home,
},
{
path: "about",
Component: About,
},
],
},
])
// Fetch parameters in components
import { useParams } from "react-router"
function Card() {
let params = useParams()
console.log(params.id)
}
Parameter Transfer
React-router transmits the parameters in three ways, which refers to the transmission of the parameters to the target route at the time of the route jump.
Query Approach
Query's method is to use ? to pass parameters, such as:
# Multiple parameters connected with &
/user?
Jump mode:
<NavLink to="/about?id=123">About</NavLink>//1. NavLink Jump
<Link to="/about?id=123">About</Link>//2. Link Jump
import { useNavigate } from 'react-router'
const navigate = useNavigate()
navigate ('/about?id=123') // 3. use navigate jump
Fetch parameters:
Acquiring parameters
import { useSearchParams } from "react-router"
const [searchParams, setSearchParams] = useSearchParams()
Console.log(searchParams.get("id")) / /accessid parameters
Acquiring parameters
import { useLocation } from "react-router"
const { search } = useLocation()
Console.log(search) //getsearch parameters?id=123
Params Method
Params is used to pass parameters such as: [name]
/user/:id
Jump mode:
<NavLink to="/user/123">User</NavLink> //1. NavLink Jump
<Link to="/user/123">User</Link> //2. Link Jump
import { useNavigate } from 'react-router'
const navigate = useNavigate()
Navigate('/user/123') / 3. use Navigate
Fetch parameters:
Use Params to view useParams
import { useParams } from "react-router"
const { id } = useParams()
Console.log(id) / /accessid parameters
State
The state is not shown in the URL, but can transmit parameters such as:
/user
Jump mode:
<Link to="/user" state={{ name: 'Xiaoman zs', age: 18 }}>User</Link> //1. Link Jump
<NavLink to="/user" state={{ name: 'Xiaoman zs', age: 18 }}>User</NavLink> //2. NavLink Jump
import { useNavigate } from 'react-router'
const navigate = useNavigate()
navigate('/user', {state: {name: 'zs', age: 18})/ 3. use navigate jump
Fetch parameters:
UseLocation to view useLocation
import { useLocation } from "react-router"
const { state } = useLocation()
Console.log(state) / /accessstate parameters
Console.log(state.name) / /getname parameters
Console.log(state.age)//Acquisitionage parameters
Summary
React Router provides three modes of transmission of parameters, each with characteristics:
Params Method (/user/:id)
- Applicable to: pass necessary path parameters (e.g. ID)
- Characteristic: ResTful, refresh not lost
- Limit: Only strings can be passed and parameters shown in URL
Query Method (/user?name=xiaoman)
- Applicable to: pass optional query parameters
- Characteristics: flexible and variable, supporting multiple parameters
- Limit: URLs may be long and parameters are publicly visible
3. State Method
- Applying to: Transmitting complex data structures
- Characteristics: Supports any type of data with parameters not shown in URL
- Limits: Refreshing may be lost and not conducive to sharing
Selection proposal: Required parameters use Params, filter conditions with Query, temporary data use with State.
Lazy.
What's lazy?
Lazy loading is an optimised technology to delay loading of components until required. This reduces the initial loading time and improves the page performance.
Lazy loads of realization
Lazy load is achieved by using lazy attributes in route objects.
import { createBrowserRouter } from 'react-router';
const sleep = (ms: number) = > new product (resolve = settimeout (resolve, ms)); / / Simulation of a different request
const router = createBrowserRouter([
{
Component: Layout,
{
path: 'about',
lazy: async () => {
await sleep (2000); / / Simulation of a walk request
const Component = await effect ('.../pages/About'); // /scramble import component
console.log(Component);
return {
Component: Component.default,
}
}
},
],
},
]);
Load only when switching to about route
:::tip
If loader is configured, loading is used every time, and if not, only once.
:::

Experience optimization
For example, about is a lazy component which, when switching to about route, is shown as a previous router, and the new component will not be displayed until the slotted component is loaded, so that the user will feel the page Carden and the user will experience it poorly.
Usage state optimization useNavigation
Quick Check Document useNavigation
- src/layout/Content/index.tsx
import { Outlet, useNavigation } from 'react-router';
import { Alert, Spin } from 'antd';
export default function Content() {
const navigation = useNavigation();
console.log(navigation.state);
const isLoading = navigation.state === 'loading';
return <div>
{isLoading ? <Spin size='large' tip='loading...' >
<Alert description="Xiaoman zs Xiaoman zs Xiaoman zs" message="Loading" type='info' />
</Spin> : <Outlet />
}
</div>
}

Performance optimization
Using lazy loads to pack, lazy loads are packed into a single document, thus reducing the size of the main package.

Route Operations
The router operation consists of two parts:
- loader
- action
Most of the normal work is done at CRUD, so that with too many interfaces the logic is complicated and difficult to maintain, so it is necessary to optimize the code by using advanced routing.
loader
Use LoaderData quick check documents
:::tip Only GET requests trigger a loader, so loaders are suitable for fetching data. :::
Before that we are RenderComponent (render component) Fetch (access to data) RenderView (render view)
After the loader is Loader (data obtained through Fetch) - useLoaderData (access data) - RenderComponent (render component)
//router/index.tsx
import { createBrowserRouter } from "react-router";
const router = createBrowserRouter([
{
path: "/",
Component: App,
loader: async () => {
const data = await response.json();
/[! code highlight]
return {
data: response.list,
message: "success",
}
},
},
]);
//App.tsx
import { useLoaderData } from "react-router";
const App = () => {
command {data, message}=useLoaderData(); /[!code highlight]
return <div>{data}</div>;
}
action
Usually for form submission, deletion, modification, etc.
UseSubmit quick check documents UseActionData Quick Check Document
:::tip Only requests such as POST, DELETE, PATCH, and PUT trigger an action, so actions are suitable for form submissions. :::
//router/index.tsx
import { createBrowserRouter } from "react-router"
const router = createBrowserRouter([
{
// path: '/index',
Component: Layout,
children: [
{
path: "about",
Component: About,
action: async ({ request }) => {
const formData = await request.formData()
create user
return {
data: table,
success: true,
}
},
},
],
},
])
//App.tsx
import { useSubmit } from "react-router"
import { Card, Form, Input, Button } from "antd"
export default function About() {
const submit = useSubmit()
return (
<Card>
<Form
onFinish={(values) => {
Submit (values, {method: "post"}) / [!code highlight] submit forms
}}
>
<Form.Item name="name" label="Name">
<Input />
</Form.Item>
<Form.Item name="age" label="Age">
<Input />
</Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form>
</Card>
)
}
Change of Status
We can work with useNavigation to manage the form submission.
- The GET submission follows:
idle -> loading -> idle
- POST submissions will be made after:
idle -> submitting ->loading -> idle
So we can control behavior in these states.
import { useNavigation, useSubmit } from "react-router";
const submit = useSubmit();
const navigation = useNavigation();
return (
<div>
{navigation.state === 'loading' && <div>loading...</div>}
<button disabled={navigation.state === 'submitting'}>Submit </button>
</div>
)
### Navigation
In React-Router V7, there are approximately four navigational methods:
1. Use `Link` component [link](./apis/link)
2. Use `NavLink` component [navlink](./apis/navlink)
3. Navigator `useNavigate`[usenavigate](./hooks/useNavigate)
4. Redirect `redirect` [redirect](./apis/redirect)
:::tip
This page is a combination of navigational links, using the corresponding links.
:::
### Border processing
Border processing consists of `Error Handling`, `ErrorBoundary` `404 pages and so on.`
### 404 Page Processing
The 404 page refers to the page displayed when the react-router route does not match, for example, our route is/home,/about, and 404 pages are displayed when you go to jump to a non-existent route, for example/aaaa.
But the 404 pages you bring with you are too ugly, and more often we need to customize 404 pages.
Configure
- Use `*` as a wildcard to show 404 pages when route does not match Noodles.
- Use `Component: NotFound` as a 404-page component
```ts
const router = createBrowserRouter([
{
path: '/index',
Component: Layout,
children: [
{
path: 'home',
Component: Home,
},
{
path: 'about',
Component: About,
},
],
},
{
path: '*', // [!code highlight] 通配符,当路由匹配不到时,显示404页面
Component: NotFound, // [!code highlight] 404页面组件
},
]);
404.tsx
import { Link } from "react-router"
export default function NotFound() {
return (
<div
style={{
height: "100vh",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
background: "#f5f5f5",
}}
>
<h1 style={{ fontSize: 96, color: "#1890ff", margin: 0 }}>404</h1>
<p style={{ fontSize: 24, color: "#888", margin: "16px 0 0 0" }}>
抱歉,您访问的页面不存在
</p>
<Link
to="/"
style={{
marginTop: 32,
color: "#1890ff",
fontSize: 18,
textDecoration: "underline",
}}
>
返回首页
</Link>
</div>
)
}

ErrorBoundary
ErrorBoundary was used to capture and process errors in route router or action.
If a loader or action throws an error, the ErrorBundary component is called.
import NotFound from "../layout/404" // 404页面组件
import Error from "../layout/error" // 错误处理组件
const router = createBrowserRouter([
{
path: "/index",
Component: Layout,
children: [
{
path: "home",
Component: Home,
ErrorBoundary: Error, //如果组件抛出错误,会调用ErrorBoundary组件
},
{
path: "about",
loader: async () => {
//throw new Response('Not Found', { status: 404, statusText: 'Not Found' }); 可以返回Response对象
//也可以返回json等等
throw {
message: "Not Found",
status: 404,
statusText: "Not Found",
data: "132131",
}
},
Component: About,
ErrorBoundary: Error, //如果loader或action抛出错误,会调用ErrorBoundary组件
},
],
},
{
path: "*",
Component: NotFound,
},
])
And returned error information can be retrieved from a book
error.tsx
import { useRouteError } from "react-router"
export default function Error() {
const error = useRouteError()
return <div>{error.message}</div>
}
API
Link
Link component is a component for navigation to other pages, and he will be rendered as a special <a> label, unlike the traditional aa label, and he will not refresh the page but manage the route through router.
Use
import { Link } from "react-router"
export default function App() {
return <Link to="/about">About</Link>
}
Parameters
to: Path to Navigatorreplace: Replace current pathstate: Status to pass to target pagerelative: Navigation relative to current pathreloadDocument: Reload Page Noodles.preventScrollReset: Whether to stop the rolling position resetviewTransition: Enable the view transition
to
to Properties are a string that indicates the path to be navigated.
<Link to="/about">About</Link>
replace
replace Properties are a boolean value that indicates whether to replace the current path and, if true, the navigation does not create a new entry in the browser's history, but replaces the current entry.
<Link replace to="/about">
About
</Link>
state
state Properties is an object that can pass parameters to the target page.
;<Link state={{ from: "home" }} to="/about">
About
</Link>
// 在目标页面获取状态
import { useLocation } from "react-router"
export default function App() {
const location = useLocation()
console.log(location.state)
return <div>Location: {location.state.from}</div>
}
relative
relative Properties are a string that indicates that the default is an absolute path relative to the current path and can be set to path if you want to use a relative path.
//默认是绝对路径
<Link relative="route" to="/about">About</Link>
//使用相对路径
<Link relative="path" to="../about">About</Link>
//例如当前的路由是/index/home,那么使用绝对路径导航到/about,会变成/about
<Link to="/about">About</Link>
//可以使用相对路径导航到/index/about
<Link relative="path" to="../about">About</Link>
reloadDocument
reloadDocument property is a boolean value that indicates whether or not to reload the page.
<Link reloadDocument to="/about">
About
</Link>
preventScrollReset
preventScrollReset property is a boolean value that indicates whether or not to prevent a rolling position reset.
<Link preventScrollReset to="/about">
About
</Link>

viewTransition
viewTransition Properties are a boolean value that indicates whether to enable the view transition and automatically increase the animation effect of the page jump.
<Link viewTransition to="/about">
About
</Link>
NavLink
NavLink is used in a manner similar to Link components, but NavLink components can be activated by route.
Use
import { NavLink } from "react-router"
export default function App() {
return <NavLink to="/about">About</NavLink>
}
Parameters (similar to Link component)
to: Path to Navigatorreplace: Replace current pathstate: Status to pass to target pagerelative: Navigation relative to current pathreloadDocument: Reload Page Noodles.preventScrollReset: Whether to stop the rolling position resetviewTransition: Enable the view transition
to
to Properties are a string that indicates the path to be navigated.
<NavLink to="/about">About</NavLink>
replace
replace Properties are a boolean value that indicates whether to replace the current path and, if true, the navigation does not create a new entry in the browser's history, but replaces the current entry.
<NavLink replace to="/about">
About
</NavLink>
state
state Properties is an object that can pass parameters to the target page.
;<NavLink state={{ from: "home" }} to="/about">
About
</NavLink>
// 在目标页面获取状态
import { useLocation } from "react-router"
export default function App() {
const location = useLocation()
console.log(location.state)
return <div>Location: {location.state.from}</div>
}
relative
relative Properties are a string that indicates that the default is an absolute path relative to the current path and can be set to path if you want to use a relative path.
//默认是绝对路径
<NavLink relative="route" to="/about">About</NavLink>
//使用相对路径
<NavLink relative="path" to="../about">About</NavLink>
//例如当前的路由是/index/home,那么使用绝对路径导航到/about,会变成/about
<NavLink to="/about">About</NavLink>
//可以使用相对路径导航到/index/about
<NavLink relative="path" to="../about">About</NavLink>
reloadDocument
reloadDocument property is a boolean value that indicates whether or not to reload the page.
<NavLink reloadDocument to="/about">
About
</NavLink>
preventScrollReset
preventScrollReset property is a boolean value that indicates whether or not to prevent a rolling position reset.
<NavLink preventScrollReset to="/about">
About
</NavLink>

viewTransition
viewTransition Properties are a boolean value that indicates whether to enable the view transition and automatically increase the animation effect of the page jump.
<NavLink viewTransition to="/about">
About
</NavLink>
Difference
Navlink will go through the following three states, and Link won't, so Navlink is an enhanced version of the klink.
active: Activated state (current route and too properties match)pending: waiting status (loader has data to load)transitioning: Transition state (activated through ViewTransion Properties)
Activate automatically
Navlink will activate automatically depending on whether the current route and tog properties match.
React-router automatically adds styles to it
a.active {
color: red;
}
a.pending {
animate: pulse 1s infinite;
}
a.transitioning {
/* css transition is running */
}
If you don't like writing styles, you can also set them directly with style properties.
<NavLink
viewTransition
style={({ isActive, isPending, isTransitioning }) => {
return {
marginRight: "10px",
color: isActive ? "red" : "blue",
backgroundColor: isPending ? "yellow" : "transparent",
}
}}
to="/index/about"
>
About
</NavLink>
:::warning
- ViewTransion requires a Google 111 version to use and be compatible

- Sending can only be used in data mode and frame mode, and the declarative path path is not available :::
redirect
Redirect is for re-direction, usually for loader, and when loader returns redirect, automatically re-direction to redirect specified route.
Cases and usage
Could not close temporary folder: %s
import { redirect } from "react-router";
{
path: "/home",
loader: async ({request}) => {
const isLogin = await checkLogin();
if(!isLogin) return redirect('/login');
return {
data: 'home'
}
}
}
scrollrestoration
Hooks
useNavigate
useNavigate is a react-router hook for programming navigation, and the route is jumped.
For example, when the countdown is over, the jump is automatically returned, for example, because this is a logical operation, at which point the jump of the component mode is inappropriate and at which point it is necessary to use a programming jump.
import { useNavigate } from "react-router"
const navigate = useNavigate()
setTimeout(() => {
navigate("/home")
}, 1000)
Parameters
Similar parameters to the Link component
- First parameter: to jump by
navigate(to) - Second parameter: options configuration object
navigate(to,options)- Replace: Replace the current route
- state: pass data
- relative: relative path
- PreventScrollReset: prevent scrolling reset
to
import { useNavigate } from "react-router" // 导入useNavigate
const navigate = useNavigate() // 获取navigate函数
navigate("/home") // 跳转路由
options-replace
Replaces the current route when skipping the page
navigate("/home", { replace: true })
options-state
Transfer data and use useLocation status properties for jump pages
navigate("/home", { state: { name: "张三" } })
options-relative
The way to jump, the default is the absolute path, which needs to be set to relative:'path' if you want to use the relative path
Detailslink-relative
navigate("/home", { relative: "path" })
options-preventScrollReset
Whether to prevent scrolling reset while jumping to page
Detailslink-preventScrollReset
navigate("/home", { preventScrollReset: true })
options-viewTransition
When you jump a page, whether to enable the view transition and automatically increase the animation effect of the page jump.
navigate("/home", { viewTransition: true })
useNavigation
What is usenavigation
useNavigation is a React-Router hook used to retrieve the navigation status of the current route.
How to use use Navigation
import { useNavigation } from "react-router"
const navigation = useNavigation()
navigation.state
idleFree statussubmittingSubmission StatusloadingLoad status
The following state conversions occur when using normal navigation or when GET forms are submitted:
idle → loading → idle
The forms submitted using POST, PUT, PATCH or DELETE will undergo the following state transformation:
idle → submitting → loading → idle
:::tip
Without loader, no loading status
:::
You can write your own logic for these states.
const navigation = useNavigation()
const isLoading = navigation.state === "loading"
const isSubmitting = navigation.state === "submitting"
const isIdle = navigation.state === "idle"
navigation.formData
Data from the form can be obtained when it is submitted using the original form <form> and is requested by POST, PUT, PATCH or DELETE.
formData is empty if requested by navigation.location.search
navigation.json
When a form is submitted, data from the form can be obtained if enctype is application/json.
navigation.text
When a form is submitted, data from the form can be obtained if enctype is text/plain.
navigation.location
The location of the current route is the same as the return value of useLocation
navigation.formAction
For example: /login, if GET is empty, if /detail/id returns /id
navigation.formMethod
For example: POST, GET, PUT, PATCH, DELETE
navigation.formEncType
For example: application/x-www-form-urlencoded, multipart/form-data, application/json text/plain
useParams
useParams is a React-router hook function to obtain route parameters.
Use
Returns the parameters matching the current URL.
import { useParams } from "react-router"
function SomeComponent() {
let params = useParams()
//params.id
return <div>{JSON.stringify(params)}</div>
}
Assuming the route is /posts/:id, the value of params is:
{
id: "123"
}
Type
function useParams<
ParamsOrKey extends string | Record<string, string | undefined> = string,
>(): Readonly<
[ParamsOrKey] extends [string] ? Params$1<ParamsOrKey> : Partial<ParamsOrKey>
>
useSearchParams
useSearchParams is a React-router hook function that captures the current URL search parameter, that is, after ?.
Use
Returns an object URLSearchParams that contains the current URL search parameters.
import { useSearchParams } from "react-router"
function SomeComponent() {
let [searchParams, setSearchParams] = useSearchParams()
}
For example, the current URL is http://localhost:5173/search?name=Stamp3&age=18
// 获取当前 URL 的搜索参数
let [searchParams, setSearchParams] = useSearchParams()
console.log(searchParams.get('name')) // 张三
console.log(searchParams.get('age')) // 18
//修改当前 URL 的搜索参数
<button onClick={() => setSearchParams(prev => {
prev.set('age','30');
prev.set('name','小满zs');
return prev;
})}>change</button>
//修改完成之后的 URL 为 `http://localhost:5173/search?age=30&name=小满zs`
Type
function useSearchParams(
defaultInit?: URLSearchParamsInit
): [URLSearchParams, SetURLSearchParams];
type ParamKeyValuePair = [string, string];
type URLSearchParamsInit =
| string
| ParamKeyValuePair[]
| Record<string, string | string[]>
| URLSearchParams;
type SetURLSearchParams = (
nextInit?:
| URLSearchParamsInit
| ((prev: URLSearchParams) => URLSearchParamsInit),
navigateOpts?: : NavigateOptions
) => void;
interface NavigateOptions {
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
}
useLocation
useLocation is a React-router hook function that captures the localization object of the current route.
Use
Returns the localization object of the current URL.
import { useLocation } from "react-router"
function SomeComponent() {
let location = useLocation()
return <div>{JSON.stringify(location)}</div>
}
Type
function useLocation(): Location
// 类型定义
interface Location<State> {
hash: string
key: string
pathname: string
search: string
state: State
}
Location
- hash
hash: string
URL Snippet identifier, beginning with #.
- key
key: string
is the only identifier for the current route.
- pathname
pathname: string
URL path name, start with /.
- search
search: string
URL search string starts with #.
- state
state: State
State = any
Passes the state object to the current path.
useLoaderData
useLoaderData is a React-router hook function that is used to obtain routed loader data.
Use
Returns data after processing
//router/index.tsx
import { createBrowserRouter } from "react-router"
const router = createBrowserRouter([
{
path: "/",
Component: App,
loader: async () => {
const response = await fetch("xxxxxxxxxx")
const data = await response.json()
return {
data: data,
message: "success",
}
},
},
])
//App.tsx
import { useLoaderData } from "react-router"
const App = () => {
const { data, message } = useLoaderData() // [!code highlight]
return <div>{data}</div>
}
:::warning
useLoaderData does not trigger fetch extra, he only reads loader returned data because there is no need to worry about redata requests
:::
useActionData
useActionData is a React-router hook function to access routed acaction data.
Use
Returns data after action is processed, usually used for error processing
//router/index.tsx
import { createBrowserRouter } from "react-router"
const router = createBrowserRouter([
{
path: "/",
Component: App,
action: async ({ request }) => {
//可以根据不同的格式获取不同的数据
const formData = await request.formData() //获取formData数据
//const json = await request.json(); //获取json数据
//const text = await request.text(); //获取text数据
const email = formData.get("email")
const password = formData.get("password")
const errors = []
if (!email) {
errors.push("Email is required")
}
if (!password) {
errors.push("Password is required")
}
return { errors }
return await createUser({ email, password })
},
},
])
//App.tsx
import { useActionData } from "react-router"
const App = () => {
const errors = useActionData() // [!code highlight]
return <div>{errors}</div>
}
useRouteError
The use of RouteError is used to access routing error messages.
If a loader or action throws an error, the ErrorBundary component is called.
import { createBrowserRouter } from "react-router"
import Error from "../layout/error"
const router = createBrowserRouter([
{
path: "/index",
Component: Layout,
children: [
{
path: "home",
Component: Home,
loader: async () => {
throw {
message: "Home Error",
status: 404,
statusText: "Not Found",
data: "132131",
}
},
ErrorBoundary: Error,
},
],
},
{
path: "*",
Component: NotFound,
},
])
In the ErrorBundary component, error information can be obtained from the useRouteError.
import { useRouteError } from "react-router"
export default function Error() {
const error = useRouteError()
return <div>{error.message}</div>
}
useSubmit
useSubmit is a React-router hook function for submitting forms.
Use
:::tip
By default, useSubmit will submit formData data, and if additional data are required, it can be passed through the second parameter submit.
:::
- FormData data submitted
import { useSubmit } from "react-router"
const formData = new FormData()
formData.append("email", "test@test.com")
formData.append("password", "123456")
const submit = useSubmit()
submit(formData)
- Submit json data
import { useSubmit } from "react-router"
const submit = useSubmit()
submit(JSON.stringify({ email: "test@test.com", password: "123456" }), {
method: "POST",
encType: "application/json",
})
- Submit text data
import { useSubmit } from "react-router"
const submit = useSubmit()
submit("test", { method: "POST", encType: "text/plain" })
- Other Organiser
import { useSubmit } from "react-router"
const submit = useSubmit()
submit(
{ email: "test@test.com", password: "123456" },
{ method: "POST", encType: "application/x-www-form-urlencoded" }
)
- Submit querystring data
import { useSubmit } from "react-router"
const submit = useSubmit()
submit(
[
["email", "test@test.com"],
["password", "123456"],
],
{ method: "POST" }
)
Zustand
Zustand

Zustand is a German word for “state”. In Chinese Damn Dent., basically each frame has its own state management tool, such as Vuex for Vue, Redux for React, and Zustand is naturally also a state management tool.
So what's the advantage of a state management tool, Zustand, compared to Redux?
Redux is an old-state management library that can perform basic functions and has a huge intermediate ecology to expand additional functions, but redux is often abused and its use is cumbersome.
LightweightZustand has a very small volume of about 1 kb.Easy to use.Zustand does not need to go throughProviderpackaged components like Redux, and Zustand provides a simple API, which is quick to start.Easy to integrate.Zustand can easily integrate with frames such as React and Vue. (Zustand also has Vue version)ExpansionZustand provides the concept of the intermediate, which can be extended by means of plugins, e.g. (persistence, walk, log records, etc.).No side effectsZustand recommends the use ofimmerfor non-variability, avoiding unnecessary side effects.

Install
![]()
npm install zustand
- The case, for example, is that we want to manage a sum as a whole, because I've had this problem in practice, a sum that involved multiple components coming and going and going and going and going and going and going and going and going and going.
Get this chapter code https://github.com/message163/react-course/tree/zustand branch zustand
- Create a store folder to create a corresponding business module below the document, such as global administration
import { create } from "zustand"
// 定义一个接口,用于描述状态管理器的状态和操作
interface PriceStore {
price: number
incrementPrice: () => void
decrementPrice: () => void
resetPrice: () => void
getPrice: () => number
}
// 创建一个状态管理器,使用 create 函数,传入一个函数,返回一个对象
/**
*
* @param set 用于更新状态
* @param get 用于获取状态
* @returns 返回一个对象,对象中的方法可以用于更新状态
*/
const usePriceStore = create<PriceStore>((set, get) => ({
price: 0, // 初始状态
incrementPrice: () => set((state) => ({ price: state.price + 1 })), // 更新状态
decrementPrice: () => set((state) => ({ price: state.price - 1 })), // 更新状态
resetPrice: () => set({ price: 0 }), // 重置状态
getPrice: () => get().price, // 获取状态
}))
export default usePriceStore
- Use in component
import usePriceStore from "./store/price"
export const App = () => {
//直接解构使用即可 把他当做一个hook使用
const { price, incrementPrice, decrementPrice, resetPrice, getPrice } =
usePriceStore()
return (
<div>
<p>价格: {price}</p>
<button onClick={incrementPrice}>增加</button>
<button onClick={decrementPrice}>减少</button>
<button onClick={resetPrice}>重置</button>
<button onClick={getPrice}>获取</button>
</div>
)
}
:::tip The zustand's set function will help us consolidate the first level of the state.
import { useState } from "react"
const [state, setState] = useState({
name: "张三",
age: 18,
price: 0,
})
setState((state) => ({
...state, // 合并第一层状态 这个操作在zustand中会自动完成所以我们就不需要写这行代码了
price: state.price + 1, // 更新状态
}))
:::
Effect Presentation

Organisation
Contents
Deep state processing
In the last chapter, we said that Zustand would merge the first level of the state, but we need to pay particular attention to the deeper state of the state. Let's show it through an example of a baby.
Foundation realization
import { create } from "zustand"
interface User {
gourd: {
oneChild: string
twoChild: string
threeChild: string
fourChild: string
fiveChild: string
sixChild: string
sevenChild: string
}
updateGourd: () => void
}
// 创建 store
const useUserStore = create<User>((set) => ({
// 初始化葫芦娃状态
gourd: {
oneChild: "大娃",
twoChild: "二娃",
threeChild: "三娃",
fourChild: "四娃",
fiveChild: "五娃",
sixChild: "六娃",
sevenChild: "七娃",
},
// 更新方法
updateGourd: () =>
set((state) => ({
gourd: {
// ...state.gourd, // 需要手动合并状态
oneChild: "大娃-超进化",
},
})),
}))
export default useUserStore
Note: If the status is not combined, the other status will be lost. Each update requires a state of manual consolidation, which becomes cumbersome in practical development.

Use immer middle
Install
npm install immer
Basic use
import { produce } from "immer"
const data = {
user: {
name: "张三",
age: 18,
},
}
// 使用 produce 创建新状态
const newData = produce(data, (draft) => {
draft.user.age = 20 // 直接修改 draft
})
console.log(newData, data)
// 输出:
// { user: { name: '张三', age: 20 } }
// { user: { name: '张三', age: 18 } }
Use in Zustand
import { create } from "zustand"
import { immer } from "zustand/middleware/immer"
// 注意:使用 immer 中间件时的特殊结构
const useUserStore = create<User>()(
immer((set) => ({
gourd: {
oneChild: "大娃",
twoChild: "二娃",
threeChild: "三娃",
fourChild: "四娃",
fiveChild: "五娃",
sixChild: "六娃",
sevenChild: "七娃",
},
updateGourd: () =>
set((state) => {
// 直接修改状态,无需手动合并
state.gourd.oneChild = "大娃-超进化"
state.gourd.twoChild = "二娃-谁来了"
state.gourd.threeChild = "三娃-我来了"
}),
}))
)
Immer rationale profile
Immer.js completes the unmovable data update by all operations of Proxy proxy objects. When you modify the data, Immer creates a copy of the modified object, changes it on the copy and then returns the modified new object, while the original object remains unchanged. This mechanism ensures the non-variability of data while providing for visual modifications.
The core rationale of Immer is based on two concepts:
-
Copy while writing (Copy-on-Write)
- When no change: Return directly to the object
- When modified: Create new object
-
Inert Agent (Lazy Proxy)
- Create proxy on demand
- Intercept through Proxy
- Delay Proxy Creation
Workflow
graph TD
A[调用 produce] --> B[创建代理 draft]
B --> C[执行 recipe 修改 draft]
C --> D{是否有修改?}
D -- 是 --> E[创建新对象:...base + ...modified]
D -- 否 --> F[直接返回 base]
Simplified realization
type Draft<T> = {
-readonly [P in keyof T]: T[P]
}
function produce<T>(base: T, recipe: (draft: Draft<T>) => void): T {
// 用于存储修改过的对象
const modified: Record<string, any> = {}
const handler = {
get(target: any, prop: string) {
// 如果这个对象已经被修改过,返回修改后的对象
if (prop in modified) {
return modified[prop]
}
// 如果访问的是对象,则递归创建代理
if (typeof target[prop] === "object" && target[prop] !== null) {
return new Proxy(target[prop], handler)
}
return target[prop]
},
set(target: any, prop: string, value: any) {
// 记录修改
modified[prop] = value
return true
},
}
// 创建代理对象
const proxy = new Proxy(base, handler)
// 执行修改函数
recipe(proxy)
// 如果没有修改,直接返回原对象
if (Object.keys(modified).length === 0) {
return base
}
// 创建新对象,只复制修改过的属性
return JSON.parse(JSON.stringify(proxy))
}
// 使用示例
const state = {
user: {
name: "张三",
age: 25,
},
}
const newState = produce(state, (draft) => {
draft.user.name = "李四"
draft.user.age = 26
})
console.log(state) // { user: { name: '张三', age: 25 } }
console.log(newState) // { user: { name: '李四', age: 26 } }
:::tip N.B.: This is a simplification that does not take into account arrays and deep-seated representation, but only fulfils its core philosophy. :::
Simplification
Remember that when we used zustand we introduced the state (the following) by deconstructing the state, but this would raise a problem, for example, that component A was used in hobby.basketball while component B was not used in hobby.basketball but was updated hobby.basketball In this state, components A and B will be re-reduced, which will lead to unnecessary rejuvenation, as component B is not used in hobby.basketball.
const { name, age, hobby, setHobbyRap, setHobbyBasketball } = useUserStore()
return (
<div className="left">
<h1>A组件</h1>
<div>
<h3>{name}</h3>
<div>
年龄:<span>{age}</span>
</div>
<div>
爱好1:<span>{hobby.sing}</span>
</div>
<div>
爱好2:<span>{hobby.dance}</span>
</div>
<div>
爱好3:<span>{hobby.rap}</span>
</div>
<div>
爱好4:<span>{hobby.basketball}</span>
</div>
<button onClick={() => setHobbyRap("只因你太美")}>改变爱好rap</button>
<button onClick={() => setHobbyBasketball("篮球")}>
改变爱好basketball
</button>
</div>
</div>
)

Status Selector
So in order to avoid the problem, we can use the state selector, which allows us to choose only the part of the state we need, so that there is no need for unnecessary retrofitting.
const name = useUserStore((state) => state.name)
const age = useUserStore((state) => state.age)
const rap = useUserStore((state) => state.hobby.rap)
const basketball = useUserStore((state) => state.hobby.basketball)

useShallow
You think it's over? No, you can think that if there's a lot of attributes, like 100, we're not going to go crazy, but if you deconstruct it, he's going to cause unnecessary rejuvenation, and it's life and death, so we can use useShallow to avoid this.
:::tip
useShallow Checks only whether the reference to the top-level object has changed, and if the reference to the top-level object has not changed (even if its internal attributes or sub-objects have changed, but these changes do not affect the reference to the top-level object), the component using the use Shallow will not be re-rendered
:::
import { useShallow } from "zustand/react/shallow"
const { rap, name } = useUserStore(
useShallow((state) => ({
rap: state.hobby.rap,
name: state.name,
}))
)

Code Fetch
store/user.ts
import { create } from "zustand"
import { immer } from "zustand/middleware/immer"
interface User {
name: string
age: number
hobby: {
sing: string
dance: string
rap: string
basketball: string
}
setHobbyRap: (rap: string) => void
setHobbyBasketball: (basketball: string) => void
}
const useUserStore = create<User>()(
immer((set) => ({
name: "坤坤",
age: 18,
hobby: {
sing: "坤式唱腔",
dance: "坤式舞步",
rap: "坤式rap",
basketball: "坤式篮球",
},
setHobbyRap: (rap: string) =>
set((state) => {
state.hobby.rap = rap
}),
setHobbyBasketball: (basketball: string) =>
set((state) => {
state.hobby.basketball = basketball
}),
}))
)
export default useUserStore
A component
import "../index.css"
import useUserStore from "../../store/user"
export default function Left() {
console.log("A组件渲染")
const { name, age, hobby, setHobbyRap, setHobbyBasketball } = useUserStore()
return (
<div className="left">
<h1>A组件</h1>
<div>
<h3>{name}</h3>
<div>
年龄:<span>{age}</span>
</div>
<div>
爱好1:<span>{hobby.sing}</span>
</div>
<div>
爱好2:<span>{hobby.dance}</span>
</div>
<div>
爱好3:<span>{hobby.rap}</span>
</div>
<div>
爱好4:<span>{hobby.basketball}</span>
</div>
<button onClick={() => setHobbyRap("只因你太美")}>改变爱好rap</button>
<button onClick={() => setHobbyBasketball("篮球")}>
改变爱好basketball
</button>
</div>
</div>
)
}
B component
import "../index.css"
import useUserStore from "../../store/user"
import { useShallow } from "zustand/react/shallow"
export default function Right() {
console.log("B组件渲染")
const { rap, name } = useUserStore(
useShallow((state) => ({
rap: state.hobby.rap,
name: state.name,
}))
)
return (
<div className="right">
<h1>B组件</h1>
<div>
<div>
姓名:<span>{name}</span>
</div>
<div>
rap:<span>{rap}</span>
</div>
</div>
</div>
)
}
css
.left {
width: 50%;
height: 100%;
border: 1px solid rgb(19, 204, 148);
height: 300px;
margin: 30px;
padding: 20px;
border-radius: 10px;
}
.right {
width: 50%;
height: 100%;
border: 1px solid rgb(214, 35, 35);
height: 300px;
margin: 30px;
padding: 20px;
border-radius: 10px;
}
.left button {
margin: 10px;
padding: 10px;
}
.right button {
margin: 10px;
padding: 10px;
}
Middle
The zustand medium is a tool for adding additional logic to the status management process. They can be used for log recording, performance monitoring, data durability, walk-through, etc.
Customising Middle
We're going to get a simple middle of the log, and we're going to learn how it works.
const logger = (config) => (set, get, api) =>
config(
(...args) => {
console.log(api)
console.log("before", get())
set(...args)
console.log("after", get())
},
get,
api
)
Parameter explanation:
-
config (outside function parameters)
- Type: Function (set, get, api)=>StoreApi
- Activation: The configuration function that originally created the store is carried by the user. The middle requires a packaging function.
-
Set (Intra-Cultural Function Parameter)
- Type: Function (partialstate) = >void
- Effect: Original status update function to modify status of store.
-
get (Inner Layer Function Parameters)
- Type: Function () = > State
- Active: Gets the current status of the store.
-
api (Inner Layer Function Parameters)
- Type: Object StoreApi
- Active: Complete API (e. g. setstate, get State, subscribe, destroy, etc.) that contains the store.
Use Example
const useUserStore = create<User>()(
immer(
logger((set) => ({
name: "坤坤",
age: 18,
hobby: {
sing: "坤式唱腔",
dance: "坤式舞步",
rap: "坤式rap",
basketball: "坤式篮球",
},
setHobbyRap: (rap: string) =>
set((state) => {
state.hobby.rap = rap
}),
setHobbyBasketball: (basketball: string) =>
set((state) => {
state.hobby.basketball = basketball
}),
}))
)
)

devtools
Devtools is a tool provided by zustand for debugging, which helps us better manage our state.
-
Need to install browser plugin
Redux DevToolsDownload Address -
Open
Redux DevToolsplugin in browser and connect to the current page

import { devtools } from "zustand/middleware"
const useUserStore = create<User>()(
immer(
devtools(
(set) => ({
name: "坤坤",
age: 18,
hobby: {
sing: "坤式唱腔",
dance: "坤式舞步",
rap: "坤式rap",
basketball: "坤式篮球",
},
setHobbyRap: (rap: string) =>
set((state) => {
state.hobby.rap = rap
}),
setHobbyBasketball: (basketball: string) =>
set((state) => {
state.hobby.basketball = basketball
}),
}),
{
enabled: true, // 是否开启devtools
name: "用户信息", // 仓库名称
}
)
)
)

persist
Persist is a tool provided by Zustand for durability that helps us better manage the state. Default is stored in localStorage and can specify storage methods
import { persist } from "zustand/middleware"
const useUserStore = create<User>()(
immer(
persist(
(set) => ({
name: "坤坤",
age: 18,
hobby: {
sing: "坤式唱腔",
dance: "坤式舞步",
rap: "坤式rap",
basketball: "坤式篮球",
},
setHobbyRap: (rap: string) =>
set((state) => {
state.hobby.rap = rap
}),
setHobbyBasketball: (basketball: string) =>
set((state) => {
state.hobby.basketball = basketball
}),
}),
{
name: "user", // 仓库名称(唯一)
storage: createJSONStorage(() => localStorage), // 存储方式 可选 localStorage sessionStorage IndexedDB 默认localStorage
partialize: (state) => ({
name: state.name,
age: state.age,
hobby: state.hobby,
}), // 部分状态持久化
}
)
)
)
Empty the Api, add a button to the page, click the button to empty the cache, and automatically add a clearStorage method to the middle of the persist.
import useUserStore from '../../store/user';
const App = () => {
const clear = () => {
useUserStore.persist.clearStorage()
}
return <div onClick={clear}>清空缓存</div>
}

Subscriptions
zustand's subscribe can subscribe to a state, which triggers a callback function when the status changes.
Synchronising folder
Whenever there is a change in the state of a store, the callback function, Also, this subscription can be subscriptiond in or outside the component is triggered, if subscription within the component needs to be placed in useEffect to prevent repetition.
const store = create((set) => ({
count: 0,
}))
//外部订阅
store.subscribe((state) => {
console.log(state.count)
})
//组件内部订阅
useEffect(() => {
store.subscribe((state) => {
console.log(state.count)
})
}, [])
Cases
For example, we need to observe changes in age, greater than or equal to 26, to suggest that we can get married, less than 26, and that, if we use the option, every update will reprogram the components, which will lead to a high degree of retrofitting.
const store = create((set) => ({
age: 0,
}))
//组件里面 age 每次更新都会重新渲染组件
const { age } = useStore(
useShallow((state) => ({
age: state.age,
}))
)
Optimizing performance, using the subscription mode, and the page is called back-to-back functions when you change, but does not render the components back.
const store = create((set) => ({
age: 0,
}))
const [status, setStatus] = useState("单身")
//只会更新一次组件
useStore.subscribe((state) => {
if (state.age >= 26) {
setStatus("结婚")
} else {
setStatus("单身")
}
})
return <div>{status}</div>
Continuously optimize that current subscriptions can trigger a callback function as long as there is any change in state within the store, and we would like to subscribe only to changes in the context and to subscribe to a single status using the intermediate subscribeWithSelector.
import { subscribeWithSelector } from "zustand/middleware"
const store = create(
subscribeWithSelector((set) => ({
age: 0,
name: "张三",
}))
)
const [status, setStatus] = useState("单身")
//订阅age的变化 并且组件渲染一次
useStore.subscribe(
(state) => state.age,
(age, prevAge) => {
if (age >= 26) {
setStatus("结婚")
} else {
setStatus("单身")
}
}
)

Supplementary use
- Subscribe returns a function to unsubscribe, which can manually unsubscribe.
const unSubscribe = useStore.subscribe((state) => {
console.log(state.age)
})
unSubscribe() //取消订阅
- When you use the
subscribeWithSelectormiddle, you will add a third parameteroptions
- comparisonFn function
- FireImmediately trigger immediately
const unSubscribe = useStore.subscribe(
(state) => state.age,
(age, prevAge) => {
console.log(age, prevAge)
},
{
equalityFn: (a, b) => a === b, // 默认是浅比较,如果需要深比较,可以传入一个比较函数
fireImmediately: true, // 默认是false,如果需要立即触发,可以传入true
}
)