2

I'm trying to create persistent state with localStorage and React hooks in Next.js SSR app and everything seems to look good but when I reloade page after update my data I'm getting error:

Warning: Text content did not match. Server: "0" Client: "5"

What can I do to repair that? This is my code:

import React, { createContext, useContext, useReducer } from 'react';
import Reducer from '../utils/Reducer';
const StoreContext = createContext();

let defaultState = {
  count: 0, 
  message: "",
  pageView: 0,
};

export const StoreProvider = ({ children }) => {

  const [state, dispatch] = useReducer(Reducer, {}, () => {

    const localData = process.browser ? localStorage.getItem('state') : null
    return localData ? JSON.parse(localData) : defaultState
  });

  return (
    <StoreContext.Provider value={{state, dispatch}}>
      {children}
    </StoreContext.Provider>
  )
}

export const useStore = () => useContext(StoreContext);

Demo in codesandbox

Klaudiusz
  • 41
  • 1
  • 4
  • Maybe this issue can help.[Warning: Prop `className` did not match.](https://github.com/zeit/next.js/issues/9914) – bcjohn Jan 25 '20 at 02:31

1 Answers1

1

That warning appears because the value is different when your application did SSR with the one rendered in client (browser).

It happens because your default value is 0, and localstorage will work in client (browser), so after your application fetch the data, it will automatically render the value from localstorage, but the value now is different with your default value rendered from SSR.

You can try the comment advice from @bcjohn, useEffect react hooks to update the value.

Darryl RN
  • 7,432
  • 4
  • 26
  • 46