Creating Forms with React & Redux

Cleaning up State on Route Change

Now we've got 3 different views, however, let's say I type in something in the login screen, go to the home page, and then go back to the sign in page. Looks like the text I entered is still there. That's because redux stores are global state, so you need to be extra careful to clean up the state when you change views.

Thankfully, life cycle hooks and combineReducers() makes this pretty easy, all you need to do is emit an action when a component will unload and return an empty object for the state. Let's do this for the Login component:

Update src/components/Login.js
// ...

const mapDispatchToProps = dispatch => ({
  // ...
  onUnload: () =>
    dispatch({ type: 'LOGIN_PAGE_UNLOADED' })

class Login extends React.Component {
  // ...

  componentWillUnmount() {

  // ...

export default connect(mapStateToProps, mapDispatchToProps)(Login);

So when the component will unmount, we'll dispatch a LOGIN_PAGE_UNLOADED action. Let's handle this action in the auth reducer.

Update src/reducers/auth.js
export default (state = {}, action) => {
  switch (action.type) {
    // ...
      return {};
    case 'ASYNC_START':
      if (action.subtype === 'LOGIN' || action.subtype === 'REGISTER') {
        return { ...state, inProgress: true };
    // ...

  return state;

So when this action gets dispatched, we'll empty out the auth state. Now you can switch back and forth between the login view and the home view, and see that the input on the login view gets cleared.

Check your work

You can view the completed & working code from this tutorial here: