• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

328
Views
Redux Toolkit - Save dark mode value to local storage

I'm currently learning redux toolkit and I want to store dark mode state in localStorage so that if the users refresh the page, selected mode stays the same. My application looks like this:

index.js

import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import darkModeReducer from "./darkModeSlice";
import App from "./App";

const store = configureStore({
  reducer: {
    darkMode: darkModeReducer,
  },
});

ReactDOM.render(
  <Provider store={store}>
      <App />
  </Provider>,
  document.getElementById("root")
);

darkModeSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  darkMode: false,
};

export const darkModeSlice = createSlice({
  name: "darkMode",
  initialState,
  reducers: {
    toggleDarkMode: (state) => {
      state.darkMode = !state.darkMode;
    },
  },
});

export const { toggleDarkMode } = darkModeSlice.actions;

export default darkModeSlice.reducer;

What would be the optimal solution for this? Please note that I only want to store the dark mode state in local storage, so if I add other reducers in the future their values ​​won't be automatically saved there.

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could change your initialState in darkModeSlice

const initialState = {
    darkMode: localStorage.getItem("darkMode") || false
}

If localstorage is undefined, it will automatically be false. And when user changes darkMode you store it with :

localStorage.setItem("darkMode", darkMode);
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error