React Redux - The Data Manager for your React App
Using React-Redux Library With A Demo Application
Since you showed interest in this blog you have done coding in react. You might have stored the data rendering for in component in a state. this data can be updated, deleted all CRUD Operations. But When the data should be passed from 1st component to 15th child component. Prop Drilling will become much pain.
Wait What is Prop Drilling ?
- Prop Drilling is passing of data from parent component to child components using props
Small Application Can Manage Easily But When The Application Scales It will be much harder to manage the state of the components Data
So What's the solution ?
This Problem Can Be solved Using Redux
Redux
- Redux is State Management Library Which All your application data will be at central place
Why Redux ?
Here our burning problem was to pass data from top to bottom here redux where the data will be at central location then no need to pass data from top to bottom all the components from the root to last child can access the application data easily
You Might Have Listened These Terms Frequently
- Reducers
- Dispatch
- Store
- Actions
Don't worry I Will Explain Them One By One
Provider : To write and read data to a central or global store first we need the access to store this will be done by The Provider API in the react redux it makes your while app accessible to store
Reducers : Reducers are plain functions which take the previous data from store and action which performs some crud operations what action tells to do and then return the state after action has taken place. Remeber reduce function in javascript which takes accumulated value and value and returns a new value the reducer is the application of reduce function.
Actions : Actions are the plain javascript object which has below pattern :
const action={
type:"CREATE_TODO",
data:{
name:"Drink Water",
isCompleted:false,
}
}
As Above you can see an object which as type of what to do from CREATE Operation and the data object is the data required tp perform the create todo operation
Store : As the name suggests the data object tree of your application which all your data in the application lies.
Dispatch : You cannot alter the store directly you need a dispatch function to mutate store like in useState of component remember ? There will be setState to Mutate The state similarly dispatch function takes action object and performs action type on store to return new state
Implementation
Installation
npm install @reduxjs/toolkit react-redux
Create Store
- Create a store.js file in which creates the store for your application
- import configureStore function from react-redux to create redux and pass reducers list in the object
import { configureStore } from '@reduxjs/toolkit'
export default configureStore({
reducer: {
toDo:toDoReducer:
},
})
Provide the created Store to your App
Go to root of the App index.js where keep your App Component as Children of Provider Component and Pass store prop which you have created above
import store from "./store";
root.render(
<Provider store={store}>
<App />
</Provider>
);
Create A Slicer
For any state to mutate redux requires dispatch and dispatch requires action so all these three can be packed in to a single file feature as we are showing demo for scalable apps it should have seperate files for actions,reducers,services etc
import { createSlice } from "@reduxjs/toolkit";
export const todoSlice = createSlice({
name: "toDO",
initialState: {
todoList: []
},
reducers: {
addToDo: (state, action) => {
state.todoList.push(action.payload);
},
deleteToDo: (state, action) => {
state.todoList.filter((toDo) => toDo._id !== action.payload);
},
markCompleted: (state, action) => {
state.todoList.map((toDo) => {
if (toDo._id === action.payload) {
toDo.completed = true;
}
});
}
}
});
export const { addToDo, deleteToDo, markCompleted } = todoSlice.actions;
export default todoSlice.reducer;
import this toDo slice in store.js file
Usage in React Component
Yayy !! So Far Now We have done the boilerplate and Now It's time to implement in UI Before That Ek Shayri Hojaye
- Sitaro Ke aage Jaha Aur Bhi Hai
- Redux Ke aage Kaam aur bhi hai
Create a file or In App.js create a html for toDo Create and List
import { useState } from "react";
import "./styles.css";
export default function App() {
const [todo, setTodo] = useState({
name: "",
completed: false
});
return (
<div className="App">
<h1>ToDo App</h1>
<div>
<h3>Create To Do</h3>
<input
placeholder="Enter ToDo"
onChange={(e) =>
setTodo({ ...todo, _id: uuidv4(), name: e.target.value })
}
/>
<button onClick={() => dispatch(addToDo(todo))}>Submit </button>
</div>
<div>
<h3>ToDo List</h3>
{todoList.map(({ _id, name, completed }) => (
<div
style={{
border: "1px solid #000",
display: "flex",
flexDirection: "column",
padding: "1rem",
gap: "1rem"
}}
>
<div key={_id}>
<span>Name : {name}</span>
</div>
<div>
<span>Status : {completed ? "Completed" : "Incomplete"}</span>
</div>
<div
style={{ display: "flex", gap: "1rem", justifyContent: "center" }}
>
<button onClick={() => dispatch(deleteToDo(_id))}>Delete</button>
<button onClick={() => dispatch(markCompleted(_id))}>
Complete
</button>
</div>
</div>
))}
</div>
</div>
);
}
useDipatch & useSlectors :
to trigger action from UI to Store dispatch function is required useDispatch is a hook which takes internally handles dispatch function bu just taking reducer function as argument
useSelector reads the data and subscribes to changes in the data from store when the data in store changes it will also change.
Add the to the App.js and test the App
//in App.js state and redux state for Todo
const [todo, setTodo] = useState({
name: "",
completed: false
});
const dispatch = useDispatch();
const todoList = useSelector((state) => state.toDo.todoList);
Anddd It's Done Congratulations You Have Made To Do App WIth Redux
Redux should Only Be Used When Needed Small Project Doen't need Redux You Can go with context api which react gives you out of the box