Blog>
Snippets

Default Export with ESM in Redux Reducers

Showcase the use of default exports when creating Redux reducers with ESM, and how to properly import them in a Redux store setup.
// counterReducer.js
// This is the reducer that will manage the state of a counter

const initialState = { value: 0 };

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { ...state, value: state.value + 1 };
    case 'counter/decremented':
      return { ...state, value: state.value - 1 };
    default:
      return state;
  }
}

export default counterReducer;
Defines a counterReducer with initial state and provides handling for 'incremented' and 'decremented' actions. It uses default export, making it the main export of the 'counterReducer.js' module.
// store.js
// This is the redux store setup

import { createStore } from 'redux';
// Import the default export from counterReducer.js under the name 'counterReducer'
import counterReducer from './counterReducer';

const store = createStore(counterReducer);

export default store;
Sets up the Redux store, importing the default exported reducer as 'counterReducer' and uses it to create the store with 'createStore'.