Utilizing Redux Toolkit with Next.js
Implement a slice with Redux Toolkit within a Next.js application, demonstrating the simplification of state management across components.
import { configureStore } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
// Create a counter slice with the slice name 'counter', initial state and reducers
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
}
}
});
// Export the reducer actions
export const { increment, decrement } = counterSlice.actions;
// Configure the store with the counter slice reducer
export const store = configureStore({
reducer: {
counter: counterSlice.reducer
}
});
// Wrap the App component with the Redux Provider and pass the store
const MyApp = ({ Component, pageProps }) => (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
export default MyApp;
This code sets up a Redux store for a Next.js application using Redux Toolkit. It creates a counter slice with increment and decrement actions, configures the store with the slice reducer, and provides the store to the React component tree via the Redux Provider component.