第六十四周总结——React18新特性的hook
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
React 18 引入了一些新的钩子特性,这些特性可以帮助我们更好地管理和组织我们的应用程序中的状态。
- useSyncExternalStore
useSyncExternalStore 是一个 React 的钩子,它可以帮助我们从外部源(例如:Redux store, RxJS subjects, or any other source)同步非React状态。
import { useSyncExternalStore } from 'use-sync-external-store/react';
import { atom } from 'jotai';
import { useAtomValue } from 'jotai/utils';
const countAtom = atom(0);
function ChildComponent() {
const count = useAtomValue(countAtom);
return <div>Count: {count}</div>;
}
- useInsertionEffect
useInsertionEffect 是一个 React 的钩子,它的行为类似于 useEffect,但它会在组件插入到 DOM 后执行,而不会导致额外的重新渲染。
import { useInsertionEffect } from 'react';
function ChildComponent() {
useInsertionEffect(() => {
// 执行一些操作,例如测量或者注册监听器
return () => {
// 在组件卸载时执行清理操作
};
}, []);
return <div>Child Component</div>;
}
- useDeferredValue
useDeferredValue 是一个 React 的钩子,它可以用来延迟更新状态,这在需要在 DOM 更新前进行状态更新时非常有用。
import { useTransition, useDeferredValue } from 'react';
function ChildComponent({ value }) {
const [isPending, startTransition] = useTransition(false);
const deferredValue = useDeferredValue(value, { timeoutMs: 3000 });
return (
<>
<button onClick={() => startTransition(() => setValue(value + 1))}>
Increase
</button>
{isPending ? 'Pending...' : null}
<div>Value: {deferredValue}</div>
</>
);
}
- useTransition
useTransition 是一个 React 的钩子,它可以用来创建一个过渡状态,在这个状态下,组件的更新会被延迟。
import { useTransition } from 'react';
function ChildComponent() {
const [isPending, startTransition] = useTransition();
return (
<>
<button onClick={() => startTransition(() => setValue(value + 1))}>
Increase
</button>
{isPending ? 'Pending...' : null}
<div>Value: {value}</div>
</>
);
}
- useMutableSource
useMutableSource 是一个 React 的钩子,它可以用来从可变源(如可观察对象)中读取数据。
import { useMutableSource } from 'react';
import { MutableSource } from 'react-isolate-components';
function ChildComponent() {
const mutableSource = useMutableSource({
source: myMutableSource,
getSnapshot: myMutableSource.get,
});
return <div>Value: {mutableSource.value}</div>;
}
以上就是这周我学习到的一些新的钩子特性,它们可以帮助我们更好地管理和组织我们的应用程序中的状态。
评论已关闭