Installation.
I use npm to install RTK and react-redux.
npm install @reduxjs/toolkit react-redux
1. Start with createSlice()
.
The example provide on the Rredux Toolkit official website is a little bit bizarre, as it started by configuring the store and providing the store to the App
component. However, if we are gonna build an application from scratch, the first thing we do is createSlice()
as it helps us to set up the slice of state, action creators, action types, and reducers in Redux.
createSlice()
receive a single configuration object as parameter.
This configuration object has four options:
name
: A string name of this slice of state, it also used as the prefix of action type.initialState
: The initial value for the slice of state.reducers
: This object contains all the reducers that use to manipulate the related state used at theinitialState
. It simplified theswtich case
syntax we use for the Redux.
Return value of createSlice()
This function mainly return an object contains name
, reducer
and actions
like this:
|
|
So, as the return value is listed, the export value should be actions
and reducer
.
|
|
Example of how to use createSlice()
|
|
2. Configuring the store.
After all the slices of state have created, the next step is create the store by using configureStore()
.
configureStore()
also receive a single configuring object as parameter.
This object has below basic options:
reducer
: This object should have all the reducers that exported from eachcreateSlice()
function.middleware
: if this option is provided, it should contain all the middleware functions that we want to added to the store. If not providedgetDefaultMiddleWare
will be use as its argument.preloadedState
: An optional initial state value to be passed to the Redux createStore function.
Basic Example of configureStore()
.
|
|
3. Provide the store to the React component.
- Put a React-Redux
<Provider>
component around your<App />
- Pass the Redux store as
<Provider store={store}>
|
|
4. Use the React-Redux useSelector/useDispatch hooks in React components
- Read data from the store with the
useSelector
hook. - Get the dispatch function with the
useDispatch
hook, and dispatch actions as needed.
Example of useSelector
& useDispatch
.
|
|
Reference
- Redux Toolkit.(2023). Retrieved from https://redux-toolkit.js.org/tutorials/quick-start