Blog>
Snippets

Managing Themes with Redux Toolkit

Use `createReducer` to toggle between light and dark themes dynamically, based on user preferences.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Action to toggle the theme
export const toggleTheme = createAction('theme/toggle');
This code defines an action called 'toggleTheme' using createAction. This action will be dispatched to toggle between light and dark themes.
const initialState = { theme: 'light' };

// Reducer to handle the theme state
export const themeReducer = createReducer(initialState, (builder) => {
  builder.addCase(toggleTheme, (state) => {
    // Toggle the theme between 'light' and 'dark'
    state.theme = state.theme === 'light' ? 'dark' : 'light';
  });
});
Here we define the initial state with 'theme' set to 'light'. We then use createReducer to define a reducer which listens to the toggleTheme action. When the action is dispatched, the reducer toggles the state's theme property between 'light' and 'dark'.