DEV Community

Cover image for REDUX TOOLKIT FUNDAMENTAL
Najmul Ovi
Najmul Ovi

Posted on

REDUX TOOLKIT FUNDAMENTAL

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:

  1. Too much code to configure store.
  2. Too much boilerplate code.
  3. Too many packages needed to install to build scalable apps.
  4. 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
Enter fullscreen mode Exit fullscreen mode

or,

npx create-react-app my-app --template redux
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize & Create Store
We can create store.js file

import { configureStore } from '@reduxjs/toolkit'

export default configureStore({
  reducer: {} //add reducers here
})
Enter fullscreen mode Exit fullscreen mode

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')
)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
  }
})
Enter fullscreen mode Exit fullscreen mode

Step 6: Dispatch Actions from UI

import { useSelector, useDispatch } from 'react-redux'
import { decrease, increase } from './counterSlice'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)