Basic usage of Redux Toolkit

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 the initialState. It simplified the swtich case syntax we use for the Redux.

Return value of createSlice()

This function mainly return an object contains name, reducer and actions like this:

1
2
3
4
5
6
7
{
    name: ,//slice name
    reducer: //reducer function that related to this slice of state
    actions: // action creator, created by the function based on the function write at reducers.
    caseReducer: // Record CaseReducer.
    getInitialState: () => state// function return state
}

So, as the return value is listed, the export value should be actions and reducer.

1
2
export const {reducerName1, reducerName2} = sliceName.actions;
export default sliceName.reducer;

Example of how to use createSlice()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const studentSlice = createSlice({
    name: 'student',
    initialState: {
        name: 'Tom'
    },
    reducers: {
        setName: (state,action)=>{
            state.name = action.payload;
        }
    }
})
export const {setName} = studentSlice.actions;
export default studentSlice.reducer;

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 each createSlice() function.
  • middleware: if this option is provided, it should contain all the middleware functions that we want to added to the store. If not provided getDefaultMiddleWare will be use as its argument.
  • preloadedState: An optional initial state value to be passed to the Redux createStore function.

Basic Example of configureStore().

1
2
3
4
5
6
7
const store = configureStore({
    reducer: {
        student: studentSlice.reducer,
        teacher: teacherSlice.reducer
    }
})
export default store;

3. Provide the store to the React component.

  1. Put a React-Redux<Provider> component around your <App />
  2. Pass the Redux store as <Provider store={store}>
1
2
3
4
5
6
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store={store}>
        <App />
    </Provider>
)

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export default function App() {
  const { name} = useSelector((state) => {
    return state.student;
  });
  const dispatch = useDispatch();
  const clickHandler = (event) => {
    console.log(event.target);
    switch (event.target.className) {
      case 'setName':
        dispatch(setName('Jane'));
        break;
      default:
        throw new Error('something wrong');
    }
  }
  return (
    <div>
      <p>{name}</p>
      <div className='buttonContainer' ref={clickRef} onClick={clickHandler}>
        <button className='setName'>setName</button>
      </div>
    </div>
  )
}

Reference

  1. Redux Toolkit.(2023). Retrieved from https://redux-toolkit.js.org/tutorials/quick-start
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
© 2020 Lingyun Yang
Built with Hugo
Theme Stack designed by Jimmy