Implementing Redux in React
Introduction:
Redux is a library for managing state in a Predictable way in JavaScript applications. Redux is not tied to React, It can be used with React, Angular, Vue, or even vanilla javascript.
Uses of Redux: Redux is used in JavaScript applications to simplify and centralize the management of application state. It provides a predictable and structured way to handle data, making it easier to manage and debug, especially as the application grows in complexity.
In Redux, there are 3 main parts:
Store: This holds the state of our application, It is used to store our state values.
Reducers: Reducer is part of the store, It is responsible for managing state changes based on dispatched actions. It takes two things: Previous state and an action.
Actions: Actions are used to send data from the application to the redux store.
Install Redux Using the Below Command:
1. npm install redux react-redux
2. npm install @reduxjs/toolkit
Note: To utilize Redux debugging, it’s necessary to install the Redux DevTools Extension on Chrome and Firefox.
Example of Store, Reducers, Actions for Book Management:
Store :
import {createStore} from ‘redux’;
const intitalState ={
books:[ ],
};
const bookReducer = (state = initiaState,action)={
if(action.type === “ADD_BOOK”){
return {…state, books: […state.books, action.payload] };
} else if (action.type === “REMOVE_BOOK”){
const updatedBooks = state.books.filter(book => book.id ! == action.payload);
return {…state, books: updatedBooks};
}
return state;
};
const store = createStore(bookReducer);
export default store;
Reducers:
const intitalState ={
books:[ ],
};
const bookReducer = (state = initiaState,action)={
if(action.type === “ADD_BOOK”){
return {…state, books: […state.books, action.payload] };
} else if (action.type === “REMOVE_BOOK”){
const updatedBooks = state.books.filter(book => book.id ! == action.payload);
return {…state, books: updatedBooks};
}
return state;
};
export default bookReducer;
Actions:
const addBook = (title,author)({
type: ‘ADD_BOOK’, payload: { id: Math.random().toString(36).substr(2, 9), title, author },
});
const removeBook = (bookid)({
type: ‘REMOVE_BOOK’,
payload: bookid,
});
Explanation:
1. store: It manages a collection of books within the application state using a reducer function. It handles adding and removing books from the list.
2. Reducer: It contains a bookReducer
function that determines how the state changes based on dispatched actions (‘ADD_BOOK’ and ‘REMOVE_BOOK’).
3. Action: It Provides action creators for adding a book and removing a book. This action contains a type and payload, allowing the reducer to update the store’s state accordingly.