Why Redux Toolkit?
We know that Redux was a popular option for state management. It makes states predictable. Reducers are pure functions that means the same state and actions are passed will always result in the same output.
Redux also easily maintainable, scalable, efficient testing, easy debugging and better performance that Redux brings to build applications.
However, this flexible and high-level state management library comes with a few challenges:
- Too much code to configure store.
- Too much boilerplate code.
- Too many packages needed to install to build scalable apps.
- Writing actions and reducers becomes more complex on large applications.
To overcome these challenges, The Redux team came up with Redux Toolkit. It's main purpose is to speed up Redux development by including Redux Core with the packages that they think are essential to build a Redux app. It also makes our code and folder structure more understandable and organized.
How We Started With Redux Toolkit?
Step 1: Packages Install
npm install @reduxjs/toolkit react-redux
or,
npx create-react-app my-app --template redux
Step 2: Initialize & Create Store
We can create store.js file
import { configureStore } from '@reduxjs/toolkit'
export default configureStore({
reducer: {} //add reducers here
})
Step 3: Provide Store in React app
In our index.js file
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Step 4: Reducers and Actions
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
increase: state => {
state.value += 1
},
decrease: state => {
state.value -= 1
}
}
})
// each case under reducers becomes an action
export const { increase, decrease } = counterSlice.actions
export default counterSlice.reducer
Step 5: Import Reducer to Store
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '.counterSlice' //import our reducer from step 4
export default configureStore({
reducer: {
counter: counterReducer //add our reducer from step 4
}
})
Step 6: Dispatch Actions from UI
import { useSelector, useDispatch } from 'react-redux'
import { decrease, increase } from './counterSlice'
Top comments (0)