Next.JS – Access `localStorage` before rendering page

You can do something like this:

  1. Use a variable in the state to prevent the page from being rendered
  2. Use componentDidMount to load data from localStorage
  3. When data is loaded, setState to allow component to be rendered.

It’s a react issue, not a next.js issue.
You could use Conditional rendering for step 1.
Also read up on state here, and lastly componentDidMount.

Update:

Nowadays, I would opt for a React hooks implementation instead, but the idea still stands. useEffect can largely accomplish this with some nuances in some situations.

I also realize that there are some possible caveats with NextJS and SSR logic specifically, so this response may not be sufficient. In such cases, I would also look into some other responses below.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)