Blog>
Snippets

Toggling Theme with Redux Actions

Demonstrate how to dispatch actions to toggle between dark and light themes from a UI component using the Redux Toolkit's `useDispatch` hook.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { IconButton } from '@mui/material';
import { DarkMode, LightMode } from '@mui/icons-material';
import { toggleTheme } from './themeSlice'; // Assuming themeSlice contains the action

const ThemeToggleButton = () => {
  const darkMode = useSelector((state) => state.theme.darkMode); // Access the current theme mode
  const dispatch = useDispatch();

  const handleToggleTheme = () => {
    dispatch(toggleTheme()); // Dispatch action to toggle the theme
  };

  return (
    <IconButton
      color="inherit"
      onClick={handleToggleTheme}
    >
      {darkMode ? <DarkMode /> : <LightMode />}
    </IconButton>
  );
};

export default ThemeToggleButton;
This snippet defines a 'ThemeToggleButton' component that toggles between light and dark modes. The 'useSelector' hook accesses the current theme mode from the Redux state, and the 'useDispatch' hook allows dispatching the 'toggleTheme' action to update the state. An 'IconButton' is used as the toggle button, showing either the 'DarkMode' or 'LightMode' icon from MUI based on the current theme mode.
import { createSlice } from '@reduxjs/toolkit';

export const themeSlice = createSlice({
  name: 'theme',
  initialState: {
    darkMode: false // Initial theme mode is assumed to be light
  },
  reducers: {
    toggleTheme: state => {
      // Toggle the theme mode
      state.darkMode = !state.darkMode;
    }
  }
});

// Export the toggleTheme action for usage across the app
export const { toggleTheme } = themeSlice.actions;

export default themeSlice.reducer;
This snippet creates a slice using Redux Toolkit's 'createSlice' function. The slice named 'theme' includes 'darkMode' in its initial state and a reducer function 'toggleTheme' to toggle its value. Actions and reducer which can be imported and used in different parts of the application are also exported.
import { configureStore } from '@reduxjs/toolkit';
import themeReducer from './themeSlice'; // Import the theme reducer

export const store = configureStore({
  reducer: {
    theme: themeReducer // Assign the theme reducer to the 'theme' key in the store
  }
});
This snippet sets up the Redux store using Redux Toolkit's 'configureStore' function. It imports the 'themeReducer' from the theme slice file and sets it under the 'theme' key in the store's reducer mapping. The resulting store will be used in the application's root component to provide Redux state.