Redux
It was first introduced to the front-end world in 2015 by Dan Abramov and Andrew Clark as a revolutionary state management library. It is now one of the most popular state management libraries on the web.
Redux is a front-end component state management system, which makes managing multiple component states easier for complex apps. React, Angular, or Vue provide components that internally manage their own states.
Redux Toolkit
I have used the Redux toolkit in my projects. Because it is easy to use and It is also easily maintainable and scalable . Also, there are many other benefits such as efficient testing, easy debugging and better performance that Redux brings to the table.
Redux Toolkit Installation
Step 1: install packages
Create a React Redux App
npx create-react-app my-app --template redux
Add the Redux Toolkit and React-Redux packages to your existing project:
npm install @reduxjs/toolkit react-redux
Step 2: Create a Redux Storeβ
Create a file named src/redux/store.js. Import the configureStore API from Redux Toolkit. We'll start by creating an empty Redux store, and exporting it:
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {},
})
Step 3: Provide the Redux Store to React
Once the store is created, we can make it available to our React components by putting a React-Redux around our application in src/index.js. Import the Redux store we just created, put a around your , and pass the store as a prop:
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './app/store'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Step 4: Create a Redux State Slice
Create a file named src/redux/slices/foodSlice.js.
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
value: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
Step 5: Add Slice Reducers to the Store
On the src/redux/store.js path add Slice reducers to the store
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'
export const store = configureStore({
reducer: {
counter: counterReducer,
},
})
Top comments (0)