Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda