The Power of createSlice in Redux toolkit
What is createSlice ?
Prior to Redux toolkit, creating actions and reducers can be long and complicated.
The createSlice function is a feature of the Redux toolkit. It brings together actions and reducers into one function. When you use createSlice it automatically generates action creators and action types that correspond to the reducers and state.
In the code snippet above, we create a slice called booksSlice using createSlice. The name field tells Redux what name to use for the slice, which will be used to generate action types. The initialState sets the initial value of the state that the slice manages. The reducers field contains an object where each key represents an action name and its corresponding value is a reducer function. These reducer functions determine how the state should change when certain actions are dispatched.
Instant action creation
When we use createSlice it automatically generates action creators for each reducer that we define in the reducers field. In our previous example, the addBook and deleteBook actions are the generated action creators. We can dispatch these actions to make changes to the state.
Handling Immutability
createSlice makes use of the Immer library to handle state updates in an immutable way. Behind the scenes, the library takes care of immutability, allowing us to write reducer logic that directly modifies the state.
领英推荐
In the above example, the reducer functions modify the state parameter directly, luckily for us Immer makes the modifications result in the creation of a new immutable object.
Immer intercepts the state changes within the reducer and ensure that the initial state remains unchanged.
Adding multiple slices to a Redux store
We can use the configureStore function in Redux toolkit to combine multiple slices into a single Redux store. Let's see how we can do this
In the above code snippet, we import our reducers (booksReducer and categoriesReducer) and then pass them as key:value pairs to the reducer option in configureStore
Conclusion
Redux Toolkit’s createSlice function makes it easier to create actions and reducers in Redux. It combines them into one function call, saving time and reducing the amount of repetitive code. It also takes care of keeping the state safe and making sure everything works smoothly. With createSlice, developers can focus on building their apps instead of getting stuck in complicated setup steps.
Full-Stack Developer@hendrik Thurau Enterprises | Angular, NodeJs, tailwind, React
10 个月Very informative ??
Helping 100+ frontend devs escape tutorial hell + build modular & scalable component-based apps using React.
10 个月?? Awesome work you're putting out here man. This is amazing ?? Rafik Mhadhbi