Dynamic Slice Injection using combineSlices
Demonstrate the technique of dynamically combining slices into the store using Redux Toolkit's combineSlices method for scalable application state.
import { configureStore } from '@reduxjs/toolkit';
import { combineSlices } from '@reduxjs/toolkit';
// Define some slices
const userSlice = createSlice({
name: 'users',
initialState: [],
reducers: {
addUser(state, action) {
state.push(action.payload);
}
}
});
const postSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
addPost(state, action) {
state.push(action.payload);
}
}
});
// Combine slices initially
let dynamicReducer = combineSlices(userSlice, postSlice);
// Configure store with the dynamic reducer
const store = configureStore({
reducer: dynamicReducer
});
Initialize the Redux store with combined slices using Redux Toolkit's combineSlices method.
// Assume we have another slice to be injected later
const commentSlice = createSlice({
name: 'comments',
initialState: [],
reducers: {
addComment(state, action) {
state.push(action.payload);
}
}
});
// Inject the additional slice dynamically at a later point of time
// For instance, this could be triggered by code-splitting when a route loads
store.replaceReducer(dynamicReducer.inject(commentSlice));
Dynamically inject an additional slice into the existing store at runtime.