Blog>
Snippets

Initializing Redux Store with Theme State

Show an example of setting up a Redux store using `configureStore` from Redux Toolkit, specifically initializing the store with a default theme state.
import { configureStore, createSlice } from '@reduxjs/toolkit';
Importing necessary functions from Redux Toolkit.
// Define the initial theme state
const themeInitialState = {
  mode: 'light' // could be 'dark' as well
};
Setting up the initial state for the theme, defaulting mode to 'light'.
// Create a slice for the theme with a toggle action
const themeSlice = createSlice({
  name: 'theme',
  initialState: themeInitialState,
  reducers: {
    toggle: state => {
      state.mode = state.mode === 'light' ? 'dark' : 'light';
    }
  }
});
Creating a slice to encapsulate theme related state and actions. Includes a toggle reducer to switch theme modes.
// Configure the store with the theme slice reducer
const store = configureStore({
  reducer: {
    theme: themeSlice.reducer
  }
});
Configuring the store with `configureStore` function, including the theme slice reducer.
export default store;
Exporting the store to be used elsewhere in the application.