Redux can be made easier with Redux Toolkit.
Redux is a good fundament for the opening. But it is recommended that you use the Redux Toolkit to make things easier. It was developed in order to resolve three common Redux concerns:
- “Configuring a Redux store is too complicated”
- “I have to add a lot of packages to get Redux to do anything useful”
- “Redux requires too much boilerplate code”
Redux Setup
Now we’ll set up Redux, Redux Toolkit, React-Redux, and Typescript type definitions. Start by running:
# npm
npm install react-redux @reduxjs/toolkit
npm install -D @types/react-redux# yarn
yarn add react-redux @reduxjs/toolkityarn add -D @types/react-redux
Creating Actions and Reducers
Let's start with creating our user Slice inside src/slices/users.ts
we’ll use createSlice, which is one of the magical functions provided by Redux Toolkit to helps us create a slice of that redux-store, which contains the reducer and actions in a single file
A basic createSlice method takes in the following:
- name: which is the name of the slice for reference
- initialState: the initial state of the reducer
- reducers: contains all the actions to mutate the reducer state
the goal of createSlice is to reduce the boilerplate required to add data to redux the canonical way
Create our rootReducer inside src/slices/index.ts
which we’ll add all our reducers
To connect reducer into Redux, we have add it to the main reducer in store/index.js
:
import {combineReducers} from '@reduxjs/toolkit';import userReducer from './users';
const rootReducer = combineReducers({
users: userReducer,
// if we need to use more reducers
});
export type RootState = ReturnType<typeof rootReducer>;export default rootReducer;
theconfigureStore
API from Redux Toolkit creates a Redux store, and also automatically configure the Redux DevToo ls extension so that you can inspect the store while developing, lets Create the store file under src/store/index.ts
import {Action, configureStore, ThunkAction} from '@reduxjs/toolkit';import {useDispatch} from 'react-redux';import rootReducer, {RootState} from '../slices';
const store = configureStore({reducer: rootReducer});
export type AppDispatch = typeof store.dispatch;
export type AppThunk = ThunkAction<void, RootState, null, Action<string>>;export const useAppDispatch = () => useDispatch<AppDispatch>();
export default store;
Provide the Redux Store to React
After that, we must connect our store to the React application. Add it to the index.ts
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import store from './store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
);
Connecting Redux to Components with useDispatch and useSelector
we can now integrate Redux with pure components using hooks!