Last updated: Apr 7, 2024
Reading timeยท2 min
To reset a component to its initial state:
setState()
function, passing it the initial
state.import {useState} from 'react'; const initialState = { name: '', country: '', salary: null, }; export default function App() { const [employee, setEmployee] = useState(initialState); const updateState = () => { setEmployee({name: 'Alice', country: 'Austria', salary: 100}); }; // ๐๏ธ Reset to the initial state const resetState = () => { setEmployee(initialState); }; return ( <div> <button onClick={updateState}>Set state</button> <button onClick={resetState}>Reset to initial state</button> <h4>{JSON.stringify(employee, null, 4)}</h4> </div> ); }
useReduce
hookTo reset a component to its initial state with the useReducer
hook:
RESET
action type in your reducer.RESET
.import {useReducer} from 'react'; const initialState = 0; function reducer(state, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'RESET': return initialState; default: throw new Error(`Unhandled expression in switch: ${action.type}`); } } export default function App() { const [count, dispatch] = useReducer(reducer, initialState); const increment = () => { dispatch({ type: 'INCREMENT', }); }; // ๐๏ธ Reset to the initial state const reset = () => { dispatch({ type: 'RESET', }); }; return ( <div> <button onClick={increment}>Increment</button> <button onClick={reset}>Reset</button> <h2>Count: {count}</h2> </div> ); }
Regardless if we use the useState hook or useReducer to manage state, we have to store the initial state in a variable in order to reset it.
We declared the initial state outside of the component to avoid re-declaring it every time the component re-renders, but chances are you won't see any noticeable difference in performance.
When you manage state using the useState
hook, all you have to do is call your
setState
function passing it the initial state.
const resetState = () => { setEmployee(initialState); };
With the useReducer
hook, you have to add an action handler for the RESET
state that returns the initial state.
function reducer(state, action) { switch (action.type) { case 'INCREMENT': return state + 1; // ๐๏ธ Reset to the initial state case 'RESET': return initialState; default: throw new Error(`Unhandled expression in switch: `); } }
And dispatch an action with a type of RESET
.
const reset = () => { dispatch({ type: 'RESET', }); };