Shadcn Hooks

useResetState

A hook to reset a state

Loading...

Installation

npx shadcn@latest add @hooks/use-reset-state
pnpm dlx shadcn@latest add @hooks/use-reset-state
yarn dlx shadcn@latest add @hooks/use-reset-state
bun x shadcn@latest add @hooks/use-reset-state

Copy and paste the following code into your project.

use-reset-state.ts
import { isFunction } from 'es-toolkit/predicate'
import { useRef, useState } from 'react'
import { useCreation } from '@/registry/hooks/use-creation'
import { useMemoizedFn } from '@/registry/hooks/use-memoized-fn'
import type { Dispatch, SetStateAction } from 'react'

type ResetState = () => void

export function useResetState<S>(
  initialState: S | (() => S),
): readonly [S, Dispatch<SetStateAction<S>>, ResetState] {
  const initialStateRef = useRef(initialState)
  const initialStateMemo = useCreation(
    () =>
      isFunction(initialStateRef.current)
        ? initialStateRef.current()
        : initialStateRef.current,
    [],
  )

  const [state, setState] = useState(initialStateMemo)

  const resetState = useMemoizedFn(() => {
    setState(initialStateMemo)
  })

  return [state, setState, resetState]
}

use-reset-state.ts
import { isFunction } from 'es-toolkit/predicate'
import { useRef, useState } from 'react'
import { useCreation } from '@/registry/hooks/use-creation'
import { useMemoizedFn } from '@/registry/hooks/use-memoized-fn'
import type { Dispatch, SetStateAction } from 'react'

type ResetState = () => void

export function useResetState<S>(
  initialState: S | (() => S),
): readonly [S, Dispatch<SetStateAction<S>>, ResetState] {
  const initialStateRef = useRef(initialState)
  const initialStateMemo = useCreation(
    () =>
      isFunction(initialStateRef.current)
        ? initialStateRef.current()
        : initialStateRef.current,
    [],
  )

  const [state, setState] = useState(initialStateMemo)

  const resetState = useMemoizedFn(() => {
    setState(initialStateMemo)
  })

  return [state, setState, resetState]
}

API

type ResetState = () => void

/**
 * A hook to reset a state
 * @param initialState - The initial state
 */
export function useResetState<S>(
  initialState: S | (() => S),
): readonly [S, Dispatch<SetStateAction<S>>, ResetState]

Credits

Last updated on

On this page