Skip to content

useSafeState

作用

用法与 React.useState 完全一样,但是在组件卸载后异步回调内的 setState 不再执行,避免因组件卸载后更新状态而导致的内存泄漏。

原理

通过 useUnmountedRef 来判断组件是否已经卸载,如果已经卸载,就不再执行 setState

源码

ts
import { useCallback, useState } from 'react'
import type { Dispatch, SetStateAction } from 'react'
import useUnmountedRef from '../useUnmountedRef'

function useSafeState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>]

function useSafeState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>]

function useSafeState<S>(initialState?: S | (() => S))
  // 标记组件是否已经卸载
  const unmountedRef = useUnmountedRef()
  const [state, setState] = useState(initialState)
  const setCurrentState = useCallback((currentState) => {
    /** if component is unmounted, stop update */
    // 如果组件已经卸载,就不再执行setState
    if (unmountedRef.current) return
    setState(currentState)
  }, [])

  return [state, setCurrentState] as const
}

export default useSafeState

如有转载或 CV 的请标注本站原文地址