Mark Thomas Miller's logo

How to reset a useReducer state

November 1, 2020

If you want to reset the state in useReducer as the result of some action, you can define an initial state and set it to this every time the reset action is triggered.

const initialState = {
  sound: "meow"
}

function reducer (state, action) {
  switch (action.type) {
    case "reset":
      return initialState
    // ...
  }
}

function Example () {
  const [state, dispatch] = useReducer(reducer, initialState)

  const reset = () => dispatch({ type: "reset" })

  return <button onClick={reset}>Reset</button>
}

If you pass in the initial state as a prop, it would look like this:

function reducer (state, action) {
  switch (action.type) {
    case "reset":
      return action.payload
    // ...
  }
}

function Example ({ initialState }) {
  const [state, dispatch] = useReducer(reducer, initialState)

  const reset = () => dispatch({ type: "reset", payload: initialState })

  return <button onClick={reset}>Reset</button>
}

According to React's docs for useReducer, you can also create the initial state lazily. useReducer takes three arguments: a reducer, an initial state, and an initializer function. If the third argument is provided, the second argument will be passed to it. As the docs say:

This lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action.

This is what this would look like:

const initializer = initialState => initialState // 🍏

function reducer(state, action) {
  switch (action.type) {
    case 'reset':
      return initializer(action.payload)
    // ...
  }
}

function Example({ initialState }) {
  const [state, dispatch] = useReducer(reducer, initialState, initializer)

  const reset = () => dispatch({ type: "reset", payload: initialState })

  return <button onClick={reset}>Reset</button>
}

Feel free to choose whichever works best for your use case. The first is the simplest, the second is great if you pass your initial state via a prop, and the third is best if you want to extract the logic for calculating the initial state outside the reducer.