useResetState
A hook to reset a state
Loading...
Installation
npx shadcn@latest add @hooks/use-reset-statepnpm dlx shadcn@latest add @hooks/use-reset-stateyarn dlx shadcn@latest add @hooks/use-reset-statebun x shadcn@latest add @hooks/use-reset-stateCopy and paste the following code into your project.
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]
}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