useResettableState()

A simple hook extending useState() with an option to reset to the evaluated initial value.

Internally this hook internally uses a second state to store the evaluated initial value.

export function useResettableState<S>(
  initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>, () => void] {
  const [evaluatedInitialState] = useState(initialState);
  const [state, setState] = useState(evaluatedInitialState);

  function reset() {
    setState(evaluatedInitialState);
  }

  return [state, setState, reset];
}

Usage

function getInitialValue() {
  // this is only called once initially. when resetting, the return value of the initial call is reused
  console.log("fetched initial value");

  return 42;
}

function Test() {
  const [progress, setProgess, resetProgress] =
    useResettableState(getInitialValue);

  return (
    <>
      <button onClick={() => setState((c) => c + 1)}>{state}</button>
      <button onClick={resetState}>Reset</button>
    </>
  );
}