Next.js Discord

Discord Forum

Integrating the Redux Toolkit with Next.

Answered
ayush posted this in #help-forum
Open in Discord
My question is can we use the redux toolkit with next. I mean i did try to use this like this
// "use client";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { Provider } from "react-redux";
import { webStore, webPersistor } from "store";
import { PersistGate } from "redux-persist/integration/react";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  // const store = useStore({ initialState: {} });
  // const { store } = initializeStore({});

  return (
    <Provider store={webStore}>
      {/* <PersistGate loading={null} persistor={webPersistor}> */}
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
      {/* </PersistGate> */}
    </Provider>
  );
 

but i am getting this

after finding out what is causing this i got to know that this is caused by server side rendering. Now I end up using the use client. this is working but as i am in root layout doesnt that is an antipattern I mean what is the benefit of using next when everything will be rendered in client side.

also as you can see in the code i have commented the persistGate when i am uncommenting it cant find why the the error coming that html and body tag are not present.
can someone help me with this.
Answered by James4u
by "Server is stateless", it's the same reason as we can't use useState in server component
View full answer

39 Replies

also my store.ts look like this
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import {
    persistStore,
    persistReducer,
    FLUSH,
    REHYDRATE,
    PAUSE,
    PERSIST,
    PURGE,
    REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";


//publication
import publicationUserSlice from "./src/publication/publicationUserSlice";

let reducers = combineReducers({
    
    publicationUserSlice,
});

const persistConfig = {
    key: "root",
    storage: storage,
    whiteList: [

    ],
    blacklist: ["toast", "showBottomNavbar", "rates", "fav-rates"],
};

const persistedReducer = persistReducer(persistConfig, reducers);

const webStore = configureStore({
    reducer: reducers,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
            },
        }),
});

export type StoreState = ReturnType<typeof reducers>;

const webPersistor = persistStore(webStore);

export { webStore, webPersistor };
if possible can you give me some codebase examples(open source) that is using next and redux toolkit
@Silver Marten
@ayush <@1072591948499664996>
Atlantic salmon
I am using redux Toolkit and it works just fine in my project,
This is my app.tsx

import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ChakraProvider } from "@chakra-ui/react";
import { fonts } from "@/styles/font";
import { Provider } from "react-redux";
import { store } from "@/store/store";


const queryClient = new QueryClient();

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <style jsx global>
        {`
          :root {
            ${fonts.montserrat.style.fontFamily}
          }
        `}
      </style>
      <Provider store={store}>
        <QueryClientProvider client={queryClient}>
          <ChakraProvider>
            <Component {...pageProps} />
          </ChakraProvider>
        </QueryClientProvider>
      </Provider>
    </>
  );
}
Ok can you share your store code
@Atlantic salmon
Atlantic salmon
import { configureStore } from "@reduxjs/toolkit";
import authSlice from "./slices/authSlice";

export const store: any = configureStore({
  reducer: {
    auth: authSlice,
    // Add other reducers here
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({ serializableCheck: true }),
});

// Infer the type of Store
export type AppStore = ReturnType<typeof store>;

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
This is a basic version of my store
Ok but are you not using persiststore
Atlantic salmon
I am not
Ok
@ayush
    <Provider store={webStore}>
      {/* <PersistGate loading={null} persistor={webPersistor}> */}
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
      {/* </PersistGate> */}
    </Provider>
this is incorrect I think
html tag should be the root element
O yes
also the correct way is to create a client component which is basically all of your client side provider wrapper
and then wrap your {children} with that component
I think you can find a good example in the official website
ok on this i have a question. if I use the seprate the provider and wrap the children with provider and the provider is "use client" now will the whole app including children is running in client side or only the provider component can you give me clarity on that. also if not how will the components run in the server without the store values
nope, as we are wrapping {children}
so only the provider is running in the client
yeah, so children is sort of a blank hole for server components
ok got it what about the access of store in server. is it expected that our code will handle if the store values are coming undefined
server is stateless - can't access to the global store
why do you need global state in the server side? @ayush
let me know if you have any questions!
actually i was thinking to prepopulate the data for the user and render it on the server. I mean why cant we.
you can fetch data on the server side, you can pre-render, no issues at all
but when it comes to global state (redux store in your case) that's all in client side
by "Server is stateless", it's the same reason as we can't use useState in server component
Answer
oh got it.
thanks.
understood
Original message was deleted
let me know if you have any more questions! otherwise feel free to Mark Solution
@ayush
sorry but how do we Mark solution here
Original message was deleted
Follow this!