Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
State and localStorage data is different after refresh

So I have a problem with state and localStorage. To be exact, whenever I nest the objects inside of the themes.dark and themes.light the results in dynamic codeblock differ after refresh even though the localStorage data is in fact correct.

import { useState, useEffect } from "react";
import store from "store2";
import "./styles.css";

const themes = {
  dark: {
    theme: "dark"
  },
  light: {
    theme: "light"
  }
};

export default function App() {
  const defaultDarkTheme = window.matchMedia("(prefers-color-scheme:dark)")
    .matches
    ? themes.dark
    : themes.light;
  const [theme, setTheme] = useState(store.get("theme") || defaultDarkTheme);

  useEffect(() => {
    store.set("theme", theme);
  }, [theme]);

  return (
    <>
      <div
        className="App"
        onClick={() =>
          theme === themes.dark ? setTheme(themes.light) : setTheme(themes.dark)
        }
      >
        {JSON.stringify(theme)}
      </div>
      {theme === themes.dark
        ? JSON.stringify(themes.dark)
        : JSON.stringify(themes.light)}
    </>
  );
}

Before refresh :

enter image description here

After refresh :

enter image description here

It's pretty problematic since after refresh instead of generating the content for dark mode it generates the content for the light one.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think it is because of your useEffect hook.

 useEffect(() => {
   store.set("theme", theme);
 }, [theme]);

I think your useEffect runs before it gets the data from the localStorage. I'm not sure this is just a hunch.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your problem is not with state or the storage. You will see your problem if you add the following line after declaring your state and refresh the page after changing it to dark. console.log(theme, themes.dark, theme === themes.dark)

Javascript only decides that two objects are equal if they refer to the exact same object. However when you get your theme object from the store, it is not the exact same object as the themes.dark object you've defined earlier.

There are multiple ways to handle a scenario like this, but I think it would be simplest if you compare some string properties of the objects, for example,

theme.theme === themes.dark.theme
        ? JSON.stringify(themes.dark)
        : JSON.stringify(themes.light)

alternatively you could define a unique identifier property on your theme object which you can use to compare instead of theme.theme or if you really want to compare the objects you could do something like

JSON.stringify(theme) === JSON.stringify(themes.dark)
        ? JSON.stringify(themes.dark)
        : JSON.stringify(themes.light)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda