/** * @file 与 useState 有关或由 useState 衍生的 hooks */ import { useEffect, useMemo, useState } from 'react' import { debounce, throttle } from '../functions/function' /** * 与 useState 的唯一区别是会以指定的间隔时间 debounce setState 的动作. * 适用于 typeahead (打字时实时搜索) 等希望控制组件重渲染频率或副作用触发频率的场景. * * @param initialValue - 初始值, 在内部会直接传给 useState * @param [wait=300] - debounce 的间隔 (ms) * @returns 返回 [state, debouncedSetState, 原始 setState] */ export const useDebouncedState = (initialValue: T, wait = 300) => { const [state, setState] = useState(initialValue) const debouncedSetState = useMemo(() => debounce(setState, wait), [wait]) return [state, debouncedSetState, setState] as const } /** * 与 useState 的唯一区别是会以指定的间隔时间 throttle setState 的动作. * 适用于希望限制 setState 触发频率, 但依然随时间均匀触发 (相较于 debounce 的效果而言). * * @param initialValue - 初始值, 在内部会直接传给 useState * @param [wait=300] - throttle 的间隔 (ms) * @returns 返回 [state, throttledSetState, 原始 setState] */ export function useThrottledState(initialValue: T, wait = 300) { const [state, setState] = useState(initialValue) const throttledSetState = useMemo(() => throttle(setState, wait), [wait]) return [state, throttledSetState, setState] as const } /** * 当 useState 的初始值不是开始就有, 而是异步获取(通常是从一个请求中获取), 需要等待时, * 可以用 useAsyncState 替代 useState. * 当初始值从 == null 的值变为 != null 的值时, useAsyncState 会进行响应, 将新的初始值进行 setState. * 当初始值从 != null 的值变为另一个 != null 的值时, useAsyncState 不会进行响应. * * @param initialValue - 将从 == null 的值变为 != null 的值的异步初始值 * @returns 同 useState 一样的 [state, setState] */ export const useAsyncState = (initialValue?: T | null) => { const [state, setState] = useState() useEffect(() => { if (initialValue != null) { setState(prevState => (prevState == null ? initialValue : prevState)) } }, [initialValue]) return [state, setState] as const }