目录从一个例子开始渲染检查工具Immer 与 UseImmerImmer是如何工作的?Immer优点使用state + ImmeruseImmer自己动手实现hooks-useImm
import { FC, useState, useEffect } from 'React';
const App: FC = () => {
const [list, setList] = useState({ a: 1 });
useEffect(() => {
setList({ a: 1 });
}, []);
console.log('测试');
return (
<>
<h1>Hello WEB3 React {list.a}</h1>
</>
);
};
export default App;
why-did-you-render, 可以在开发时,帮你检测无意义的渲染
yarn add @welldone-software/why-did-you-render -D
/// <reference types="@welldone-software/why-did-you-render" />
import React from 'react';
if (process.env.node_ENV === 'development') {
// eslint-disable-next-line
const whyDidYouRender = require('@welldone-software/why-did-you-render');
whyDidYouRender(React, {
onlyLogs: true,
titleColor: 'green',
diffNameColor: 'darkturquoise',
trackHooks: true,
trackAllPureComponents: true,
});
}
要解决这个问题,需要我们使用到Immer
import { FC, useEffect } from 'react';
import { useImmer } from '@hooks/useImmer';
const App: FC = () => {
const [list, setList] = useImmer({ a: 1 });
useEffect(() => {
// setList({ a: 1 });
setList(draft => {
draft.a = 1;
});
}, []);
console.log('测试');
return (
<>
<h1>Hello Web3 React {list.a}</h1>
</>
);
};
export default App;
观察控制台,发现已经没有无意义渲染的提示了,It's wonderful!
useEffect(() => {
// setList({ a: 1 });
setList(draft => {
draft.a = 1;
});
},[]);
import { useCallback, useState } from 'react';
import { produce, Draft, freeze } from 'immer';
export type DraftFunction<S> = (draft: Draft<S>) => void;
export type Updater<S> = (arg: S | DraftFunction<S>) => void;
export type ImmerHook<S> = [S, Updater<S>];
export function useImmer<S = any>(initialState: S | (() => S)): ImmerHook<S>;
export function useImmer<T>(initialState: T) {
// const [state, setState] = useState(initialState);
// 冻结 state,第二参数 true,表示深度冻结,对象不能修改了
const [value, updateValue] = useState(() =>
freeze(typeof initialState === 'function' ? initialState() : initialState, true)
);
// 使用 useCallback,放置组件间传递,产生句柄
return [
value,
useCallback((updater: Updater<T>) => {
if (typeof updater === 'function') {
updateValue(produce(updater));
} else {
updateValue(freeze(updater));
}
}, []),
];
}
以上就是一文详解React渲染优化之useImmer的详细内容,更多关于React渲染优化useImmer的资料请关注编程网其它相关文章!
--结束END--
本文标题: 一文详解React渲染优化之useImmer
本文链接: https://lsjlt.com/news/212767.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0