X _jagan_ X
X _jagan_ X

Reputation: 103

next-redux-wrapper HYDRATE getting called multiple times

I am starting a new next js project,we are migrating from a normal react app to a next app. we intend to use redux toolkit for our global state management and we are using server side rendering.so we came across next-redux-wrapper npm package which looked like it solves most of our problems with redux and ssr but form some reason when ever we use server side rendering on one of the pages the HYDRATE action from next-redux-wrapper is getting called atleast twice sometimes even 4 times.What exactly is going wrong because the article i referred to seems to work fine,i have attached my Redux store details and the Redux slice details,and my getServerSideProps function details.

import { createStore, applyMiddleware, combineReducers } from "redux";
import count from "../ReduxSlices/CounterSlice";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import { configureStore } from "@reduxjs/toolkit";

const combinedReducer = combineReducers({
  count,
});

const reducer = (state, action) => {
  if (action.type === HYDRATE) {
    const nextState = {
      ...state, // use previous state
      ...action.payload, // apply delta from hydration
      count: {
        count: state.count.count + action.payload.count.count,
      },
    };

    return nextState;
  } else {
    return combinedReducer(state, action);
  }
};

export const makeStore = () =>
  configureStore({
    reducer: reducer,
  });

export const wrapper = createWrapper(makeStore, { debug: true });

and my Redux slice is

import { createSlice } from "@reduxjs/toolkit";
import { HYDRATE } from "next-redux-wrapper";

const initialState = {
  count: 0,
};

const counterSlice = createSlice({
  name: "counter",
  initialState: initialState,
  reducers: {
    increment: (state) => {
      state.count = state.count + 1;
    },
  },
});

export const { increment } = counterSlice.actions;
export default counterSlice.reducer;

and finally this is how i dispatch an action inside getServerSideProps

export const getServerSideProps = wrapper.getServerSideProps(
  (store) => async () => {
    store.dispatch(increment());
    console.log("server", new Date());
  }
);

The console log is logging only once but the HYDRATE action is getting dispatched atleast two times...any insight will be helpful,thank you.

Upvotes: 4

Views: 2667

Answers (1)

user490905
user490905

Reputation: 43

I had the same issue. Disabling react strict mode worked for me.

const nextConfig = {
  // reactStrictMode: true,
  ...
}
module.exports = nextConfig

Upvotes: 4

Related Questions