How to persist custom Material UI theme using Redux Toolkit and Local Storage in React

How to persist custom material UI theme using Redux toolkit and react

What you will learn:

In this article, I would assume,

Our Goal

What we will do to achieve our goal,

1. Install Redux Toolkit, React-Redux, and set up a global state for theme toggling

# If you use npm:
npm install @reduxjs/toolkit react-redux
Or
#if you use Yarn:
yarn add @reduxjs/toolkit react-redux

2. Install Material UI and set up custom theme palettes for light and dark theme

// with npm
npm install @mui/material @emotion/react @emotion/styled
// with yarn
yarn add @mui/material @emotion/react @emotion/styled

3. Use components from Material UI to build a basic UI

# npm
npm install @mui/icons-material
#yarn
yarn add @mui/icons-material

4. Use local storage for persisting our theme

const initialState = { 
darkMode: !!JSON.parse(localStorage.getItem("darkMode")),
};
const isDarkMode = !!JSON.parse(localStorage.getItem("darkMode"));

localStorage.setItem("darkMode", !isDarkMode);
store.dispatch(toggleTheme())

--

--

CoffeeBeans helps small, medium and large businesses unlock the true potential of technology and AI to solve some of their most pressing challenges

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store