How to properly hydrate Redux state in NextJS on page refresh? How to properly hydrate Redux state in NextJS on page refresh? typescript typescript

How to properly hydrate Redux state in NextJS on page refresh?


Had the same issue today. The problem is that we need to decouple the client storage from the page rendering and move it into useEffect where the component is mounted. The basic idea is, you first render the page fully and then update the page using the clients storage information.

Directly incorporating the clients local storage can/will interfere with the hydration.

Here is a code sample that i use

export default const MenuBar = () => {  const isLoggedIn = useSelector((state) => state.isLoggedIn);  useEffect(() => {    // loads from clients local storage    const auth = loadAuthenticationToken();     if (auth !== null) {      // updates the store with local storage data      dispatch(actions.jwtTokenUpdate(auth));     }  }, [dispatch]);    if (isLoggedIn) {    return <p>you are logged in</p>;  } else {    return <p>please log in</p>;  }}

For reference, a github issue on NextJS: https://github.com/vercel/next.js/discussions/17443

And a blog post where window access for rendering is required: https://dev.to/adrien/creating-a-custom-react-hook-to-get-the-window-s-dimensions-in-next-js-135k


It is mentioned in the doc that if you use getInitialProps in _app.js, you will lose the static optimization. I don't know why you are using redux on the server side, personally I will advise you to only use it on the client side and you won't need to use next-redux-wrapper anymore because it uses getInitialProps under the hood.

The example with redux-toolkit


Also a note, next-redux-wrapper uses getInitialProps on the app.js/ts when you wrap it with your store. So when you use this library and wrap your app with it you will automatically lose static optimization.