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

180
Vistas
How to change state when localStorage value changed in Next.js?

How to change state when localStorage value changed. For example, I have a language switching button, like French and English, when I click English, it will be storing to localStorage, when I click English it will also.

When I click the French the whole project need to see in French, also when I click English, want to do like that, it So how can I change state when I update localStorage?

<button onclick={()=>localStorage.setItem("language",'english')}>English</button>
<button onclick={()=>localStorage.setItem("language",'french')}>French</button>
let language;
if (typeof window !== "undefined") {
  if (localStorage.getItem("language") === null) {
    language = "english";
  }

  if (localStorage.getItem("language") !== null) {
    language = localStorage.getItem("language");
  }
}

const [langu, setLangua] = useState(language);

console.log(langu);

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

One way to achieve this that wouldn't change that much your current structure is first to change your buttons to this:

<button
  onclick={() => {
    localStorage.setItem("language", "english");
    window.dispatchEvent(new Event("storage"));
  }}
>
  English
</button>
<button
  onclick={() => {
    localStorage.setItem("language", "french");
    window.dispatchEvent(new Event("storage"));
  }}
>
  French
</button>

And then set up inside the component where you have setLangua and langu an useEffect that would listen to changes in the localStorage and update the state:

useEffect(() => {
  const listenStorageChange = () => {
    if (localStorage.getItem("language") === null) {
      setLangua("english");
    } else {
      setLangua(localStorage.getItem("language"));
    }
  };
  window.addEventListener("storage", listenStorageChange);
  return () => window.removeEventListener("storage", listenStorageChange);
}, []);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can setLangua at the same time as putting it in local storage. Or you can subscribe to local storage changes with the useEffect hook.

    import { useCallback, useEffect, useState } from 'react'

    const [userLang, setUserLang] = useState('english')

    const getLangFromLocalStorage = useCallback(() => {
        return localStorage.getItem('userLang');
    }, []);

    useEffect(() => {
      function checkUserLang() {
        const value = getLangFromLocalStorage()
    
        // Do with value what you want
    
        if (value) {
          setUserLang(value)
        }
      }
    
      window.addEventListener('storage', checkUserLang)
    
      return () => {
        window.removeEventListener('storage', checkUserLang)
      }
    }, [])

    // Set userLang initially when component did mount

    useEffect(() => {
        const value = getLangFromLocalStorage();
        if (value) {
            setUserLang(value);
        }
    }, []);

Note: This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

about 4 years ago · Juan Pablo Isaza Denunciar

0

you need set it in useEffect hook, with empty dependences, it will run only when the component mount.

const [langu,setLangua] = useState(language)
useEffect(() => {
let language = ""
if (typeof window !== 'undefined') {
    if ( localStorage.getItem("language")  === null) {
        language = "english"
    }

    if ( localStorage.getItem("language")  !== null) {
        language = localStorage.getItem("language")
    }
}
setLanguage(language)
}, [])
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