useResetState

Tags:

A React Hook similar to React.useState, but it additionally provides a reset function to reset the state back to the initial value.

Scenes

  • State Initialization and Resetting: Allows resetting the state back to its initial value within the component's lifecycle
  • Interactive Element State Management: Used for managing resettable states like scores, steps, etc.
  • ...

Demo

Source
State:
0
Initial State:
0

Usage

const [name, setName, resetName, initialName] = useResetState('Bob') // Change the state setName('Amy') // Reset the state to the initial value resetName() // Reset the state to a specified value and simultaneously modify the initial value to that specified value resetName('Lily') console.log(name, initialName) // Lily, Lily

Source

Click links below to view source on GitHub.

API

const [state, setState, reset, initialState] = useResetState(initialState, options)

InitialState

The initial value of the state.

Options

For more details, please see useSafeState#options.

Returns

type UseResetStateReturns = readonly [T, ReactSetState<T>, (initialState?: T) => void, T]

For more details, please see useSafeState#returns.