import { configureStore, combineReducers } from '@reduxjs/toolkit'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; // localStorage import counterReducer from './features/counterSlice'; const persistConfig = { key: 'root', storage, whitelist: ['counter'], // only counter will be persisted };
export default function ReduxProvider({ children }: { children: React.ReactNode }) { const storeRef = useRef<AppStore>(); if (!storeRef.current) { storeRef.current = makeStore(); } return <Provider store={storeRef.current}>{children}</Provider>; }
'use client'; import { useRef } from 'react'; import { Provider } from 'react-redux'; import { makeStore, AppStore } from './store'; the complete guide 2024 incl nextjs redux free download new
const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, setValue: (state, action: PayloadAction<number>) => { state.value = action.payload; }, }, });
import ReduxProvider from '@/lib/redux/ReduxProvider'; export default function RootLayout({ children }) { return ( <html lang="en" suppressHydrationWarning> <body> <ReduxProvider> {children} </ReduxProvider> </body> </html> ); } ❌ Wrong (Server Component): import { configureStore
const initialState: CounterState = { value: 0 };
const persistedReducer = persistReducer(persistConfig, rootReducer); combineReducers } from '@reduxjs/toolkit'
return ( <ul> {posts?.map(post => <li key={post.id}>{post.title}</li>)} </ul> ); }