React Native
Slice
Learn state slices with createSlice.
createSlice
createSlice is RTK's most important function. A slice is an object containing name, initialState and reducers. RTK automatically generates an action creator and action type for each function in reducers. This removes the need for separate files.
Example: const counterSlice = createSlice({ name: 'counter', initialState: 0, reducers: { increment: (state) => state + 1 } }). counterSlice.actions.increment is an action creator; counterSlice.reducer is the reducer itself. A slice keeps a piece of state and the functions that change it together.
The reducers field
The reducers object lists the functions that change state. Each function takes two parameters: state and action. RTK uses the immer library so it looks like you can mutate state directly; under the hood it still does an immutable update.
Example: increment: (state) => state + 1 or addBy: (state, action) => state + action.payload. In the second example action.payload carries the value sent during dispatch. RTK wraps this function into an action creator that you can call as addBy(value).
Exercise Write the counterSlice
Complete the empty file. Import createSlice from @reduxjs/toolkit. Define counterSlice: name: 'counter', initialState: 0, reducers: { increment: (state) => state + 1, decrement: (state) => state - 1 }. Add export default counterSlice.reducer and export const { increment, decrement } = counterSlice.actions.
Show example solution
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: (state) => state + 1,
decrement: (state) => state - 1,
},
});
export default counterSlice.reducer;
export const { increment, decrement } = counterSlice.actions;
Test yourself
-
Write the slice name
createSlice({
name: '____',
initialState: 0,
reducers: {}
})
Show answer
createSlice({
name: 'counter',
initialState: 0,
reducers: {}
})
-
Match the slice parts
- name
- Slice name
- initialState
- Initial value
- reducers
- Mutating functions
- actions
- Action creators
-
What does createSlice produce?
- Both a reducer and action creators
- Only a reducer
- Only a store
- Only a style
Show answer
Only a reducer — createSlice produces both a reducer and action creators.
Next lesson: useDispatch