Here we use the Redux variant family , , , , for handle all state managements system. The installation method is as follows below.
Step 1: Set up STORE configs
Adding file & code in ./src/lib/redux/store.js. This is configs supported for handle SSR state & CSR state.
import { createStore, applyMiddleware } from 'redux';
import { createWrapper } from 'next-redux-wrapper';
import thunkMiddleware from 'redux-thunk';
import combinedReducer from './reducers';
// BINDING MIDDLEWARE
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
const makeStore = ({ isServer }) => {
if (isServer) {
//If it's on server side, create a store
return createStore(combinedReducer, bindMiddleware([thunkMiddleware]));
} else {
//If it's on client side, create a store which will persist
const { persistStore, persistReducer } = require('redux-persist');
const storage = require('redux-persist/lib/storage').default;
const persistConfig = {
key: process.env.NEXT_PUBLIC_APP_NAME ? process.env.NEXT_PUBLIC_APP_NAME : 'nextjs',
whitelist: ['register', 'auth'], // only counter will be persisted, add other reducers if needed
storage, // if needed, use a safer storage
};
const persistedReducer = persistReducer(persistConfig, combinedReducer); // Create a new reducer with our existing reducer
const store = createStore(persistedReducer, bindMiddleware([thunkMiddleware])); // Creating the store again
store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store;
}
};
export const wrapper = createWrapper(makeStore);
Step 2: Set up reducers configs
Adding file & code in ./src/lib/redux/reducers.js.
import { combineReducers } from 'redux';
import count from 'store/example-redux/count/reducer';
import tick from 'store/example-redux/tick/reducer';
const combinedReducer = combineReducers({
count,
tick,
});
export default combinedReducer;
Step 3: Init actions & reducers
We have 2 examples related to using a reducer. Adding action & reducer in
First we make count reducer. Adding file & code in ./src/store/example-redux/count/action.js & ./src/store/example-redux/count/reducer.js