How to reset state in Redux?

In this article, we'll show you how to easily reset the state in Redux using the RESET_STATE action and the createStore() function.

To reset the state in Redux, you can define a RESET_STATE action and then dispatch it, which will reset the state to its initial value. Here's an example:

const initialState = {
count: 0,
isLoading: false,
error: null,
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
case 'LOADING':
return { ...state, isLoading: true };
case 'ERROR':
return { ...state, error: action.error };
case 'RESET_STATE':
return initialState;
default:
return state;
}
}

To reset the state, you can dispatch the RESET_STATE action like this:

dispatch({ type: 'RESET_STATE' });

Alternatively, you can create a new store instance with the createStore() function and initialize it with the initial state to completely reset the state.

import { createStore } from 'redux';
const store = createStore(reducer, initialState);

Keep in mind that resetting the state will also reset any changes that have been made to the state, so use this approach with caution.


September 01, 2022
15692