useResettableState

Extends standard state management with a memoized reset mechanism to revert to the initial value.

Tip

Highly useful for complex forms or filters. Instead of manually setting every field back to its default, a single call to reset() restores the state to its exact initialState.

Installation

bash

Description

The useResettableState is a specialized wrapper around useState that captures the initial value upon the first render. It provides an explicit reset function that, when called, restores the state to its original provided value, regardless of subsequent updates.

This hook is particularly useful for managing temporary inputs, filters, or complex forms when a Discard Changes or Reset to Default feature is required. It handles both direct values and lazy initialization functions identically to the native useState API.

Parameters

NameTypeDescription
initialStateT Generic | (() => T Generic)The initial state value or a function that returns the initial value.

Return values

NameTypeDescription
stateT GenericThe current state value.
setStateDispatch<SetStateAction<T Generic>>The standard React function to update the state.
reset() => voidA memoized function that resets the state to the capture initial value.

Demo

Resettable State

{
  "category": "all",
  "query": "",
  "sortBy": "relevance"
}

Source code

tsx