Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

289
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!