Using Redux Toolkit’s createSlice
Show how to define a slice of state using createSlice in Redux Toolkit and integrating it into the store.
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice'; // import the slice
export const store = configureStore({
reducer: {
counter: counterReducer, // hook the slice into our store
},
});
This piece of code creates a Redux store and integrates the counter slice reducer into it. The `configureStore` method is provided by Redux Toolkit to simplify store setup. The `counterReducer` is imported from a file where it's defined and then added to the store under the `counter` key.
import { createSlice } from '@reduxjs/toolkit';
// Define initial state for the counter
const initialState = {
value: 0,
};
// Create a slice for the counter feature
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
// Export the reducer actions and reducer
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
This code snippet demonstrates how to use `createSlice` from Redux Toolkit to define a slice of state for a counter feature. The slice includes the slice name, initial state, and reducers for incrementing and decrementing the value, as well as an additional reducer that increments by a specific amount. The reducers manage state changes, and exported actions allow the rest of the app to interact with the state.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Counter App</title>
</head>
<body>
<div id="app">
<!-- This is where our counter app will be displayed -->
</div>
<script src="./main.js"></script>
</body>
</html>
Basic HTML structure for the counter app. It defines where the counter will be rendered within the `div#app` tag. It links to the JavaScript file 'main.js' where the Redux store and counter UI logic will be executed.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
}
#app {
text-align: center;
}
Simple CSS to style the counter app. It centers the contents of the body element in the viewport and resets the default margin. The `#app` gives a text-align style to the counter container for better visual.