Trying to not fire a transition event when reloading the page

Viewed 39
import { IconButton } from "@mui/material";
import React, { useState, useEffect } from "react";
import { Brightness4, Brightness7 } from "@mui/icons-material";

const ThemeChanger = () => {
  const [themeState, setThemeState] = useState(false);

  useEffect(() => {
    const getTheme = localStorage.getItem("Theme");
    if (getTheme === "dark") {
      setThemeState(true);
    } else {
    }
  }, []);

  useEffect(() => {
    if (themeState) {
      localStorage.setItem("Theme", "dark");
      document.body.classList.add("dark-mode");
    } else {
      localStorage.setItem("Theme", "light");
      document.body.classList.remove("dark-mode");
    }
  }, [themeState]);

  return (
    <div>
      <IconButton
        className="icon-button"
        style={{ marginTop: "16px" }}
        onClick={() => {
        setThemeState(!themeState);
        document.body.classList.add("dark-light-toggle-transition");
        }}
      >
        {themeState ? <Brightness4 /> : <Brightness7 />}
      </IconButton>
    </div>
  );
};

export default ThemeChanger;

I am trying to make the former component to not fire the event of the transition that I have in "dark-mode" when I reload the page. The component is capable of toggling a dark mode.

I tried a bit of jQuery and the window.performance event but I could not make it work. I think the solution is not that hard but I am really loaded and my brain is not functioning anymore. Is there anyone who could help me?

P.S. I used a "preload" class with jQuery and set the class of the body into transition: none, however the problem is the useEffect as when the state is true it always adds the "dark-mode" class.

Thanks in advance!

EDIT: Actually I made it work. I just made a class called "dark-light-toggle-transition" which essentially is doing the work for me. I put it inside the jsx ThemeChanger component so it is only applied when I press the toggle button! If anyone needs more information, you can send me here!

0 Answers
Related