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

291
Vistas
useState and localStorage in Next.js with SSR

in the code below I'm keep getting this error: "localstorage is not defined" I'm pretty sure this happens because next.js is trying to render the page on the server. I tried to put the const [advancedMode, setAdvancedMode] = useState( localStorage.getItem("advancedMode") === "true" ? true : false ); inside useEffect but it does not work. Any idea?

import { useState, useEffect, useRef } from "react";
import Head from "next/head";
import ReactGA from "react-ga";

const Home = () => {
  const isMountedRef = useRef(null);
  const [display, setDisplay] = useState("");
  const [error, setError] = useState("");
  const [advancedMode, setAdvancedMode] = useState(
    localStorage.getItem("advancedMode") === "true" ? true : false
  );
  const [searchTerm, setSearchTerm] = useState("");
  
  // Some other code...

I have also tried the code below but then I get an error "advancedMode is not defined"

if (typeof window !== "undefined") {
    const [advancedMode, setAdvancedMode] = useState(
      localStorage.getItem("advancedMode") === "true" ? true : false
    );
  } else {
    const [advancedMode, setAdvancedMode] = useState(false);
  }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Before accessing the localStorage, you need to check if you are on server or client. You can do so by checking type of window object.

if (typeof window === "undefined") {
  // You are on server
} else {
  // You are on client, and can access the localStorage
}
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