Blog>
Snippets

Creating a Theme Slice using createSlice

Provide a sample code for creating a ‘themeSlice’ that contains the theme's state and reducers to handle theme changes using Redux Toolkit's `createSlice`.
import { createSlice } from '@reduxjs/toolkit';

// Define the initial state of the theme's slice
const initialState = {
    mode: 'light' // Default theme mode
};

// Create themeSlice using createSlice from Redux Toolkit
export const themeSlice = createSlice({
    name: 'theme', // The name used in action types
    initialState, // The initial state of the theme reducer
    reducers: {
        // Reducer to toggle between 'light' and 'dark' mode
        toggleTheme: (state) => {
            state.mode = state.mode === 'light' ? 'dark' : 'light';
        }
    }
});

// Export the action creator
export const { toggleTheme } = themeSlice.actions;

// Export the reducer
export default themeSlice.reducer;
This JavaScript code creates a Redux slice named 'themeSlice' using the 'createSlice' API from Redux Toolkit. It initially sets the theme mode to 'light'. A reducer function 'toggleTheme' is defined to switch the theme mode between 'light' and 'dark'. The action creators and the reducer function are exported for use in the Redux store.