Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How do i make a toggle save its state between React Routes

I'm trying to build a dark mode toggle in JS using React. I'm using Material-UI to design my page and I've managed to make the button change the theme of my whole page when clicked. My issue is that whenever I refresh or change the Routes, the button state doesn't get carried over. Is there anything I'm missing?

This is the code for my button:

export default function ThemeSwitch({ toggleDark, settoggleDark }) {
  const handleModeChange = () => {
    settoggleDark(!toggleDark);
  };
  return (
    <div className="theme-btn">
      <IOSSwitch
        checked={toggleDark}
        onChange={handleModeChange}
        name="toggleDark"
        color="default"
      />
    </div>
  );
}

And this is my App.js:

function App() {
  const [toggleDark, settoggleDark] = useState(false);

  const myTheme = createTheme({
    palette: {
      mode: toggleDark ? "dark" : "light",
      primary: {
        main: "#ff1744",
      },
      secondary: {
        main: "#880e4f",
      },
    },
  });

  return (
    <Router>
      <ThemeProvider theme={myTheme}>
        <CssBaseline />
        <Navbar />
        <ThemeSwitch
          toggleDark={toggleDark}
          settoggleDark={settoggleDark}
          className="theme-btn"
        />
        <UserAuthContextProvider>
          <Routes>
            <Route
              path="/"
              element={
                <ProtectedRoute>
                  <Hero />
                </ProtectedRoute>
              }
            />
            <Route path="signup" element={<SignUp />} />
            <Route path="signin" element={<SignIn />} />
          </Routes>
        </UserAuthContextProvider>
      </ThemeProvider>
    </Router>
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In order to maintain the value, you can use localStorage instead of react state.

Whenever you set the state save it in local storge like:

localStorage.setItem("toggleDark", true);

And get the state by using

localStorage.getItem("toggleDark");
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!