function useSafeState(initialState) {
  const isMounted = useIsMounted()
  const [state, setState] = React.useState(initialState)

  const safeSetState = React.useCallback(
    value => {
      scheduleMicrotask(() => {
        if (isMounted()) {
          setState(value)
        }
      })
    },
    [isMounted]
  )

  return [state, safeSetState]
}
This hook is a safe useState version which schedules state updates in microtasks
to prevent updating a component state while React is rendering different components
or when the component is not mounted anymore.