Redux For Beginners
Tags: redux, react, tutorial, webdev
Published: 2024-06-08 18:58:43

## **Basic Overview 📖**

- **Why Redux is needed ??**

**Ans :** In large-scale applications with numerous interdependent components, maintaining the state for each component can become highly complex and cumbersome. Shifting components within such a system necessitates adjustments not only to their individual states but also to the states of all related components. React-Redux simplifies this process significantly. It effectively addresses the issue of "props drilling," where props must be passed through multiple layers of components, thereby streamlining state management and enhancing maintainability.

**Define Redux:** Redux is a library for managing global application state. Redux is typically used with the React-Redux library for integrating Redux and React together. 

## **Redux Architecture: ⚙️**


![redux architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p48eaykmypt4d90tt6lv.png)

- **Action Creation:** When a user interacts with the UI and triggers an event, an action is created. An action is a plain JavaScript object that describes what happened and typically contains a type and payload.

- **Event Dispatcher:** This action is dispatched to the Redux Store via the dispatch function. The dispatch function is responsible for sending the action to the Redux Store.

- **Reducers:** The Redux Store then uses reducers to handle the action. Reducers are pure functions that take the current state and the dispatched action as arguments, process the action, and return a new state.

- **Store Update:** The Redux Store updates its state with the new value returned by the reducer. Since reducers are pure functions, they ensure that the state updates are predictable and consistent.

- **State Subscription:** Components that have subscribed to the Redux Store are notified of the state changes. These components can then re-render with the updated state, ensuring the UI is always in sync with the application state.

**How Redux solve the problem ??**
**Ans :** Redux solves state management problems in large-scale React applications by centralizing the state in a single store called the Redux Store. This architecture eliminates the issue of prop drilling, where props must be passed through multiple layers of components. Instead, all state is managed in one place, making it easier to maintain and update. When a user interacts with the UI, an action is dispatched to the Redux Store. Reducers, which are pure functions, then process these actions to update the state. Components subscribed to the store are notified of these changes and re-render accordingly, ensuring the UI stays in sync with the application state. This centralized, predictable state management streamlines complex interactions and enhances maintainability.

-----------------------------
## **Commands and Methods:**
-> **createStore from redux lib** : use to create the redux store.

-> **Provider from react-redux lib** : Act as a provider for the app which use the store as props

-> **reducer** : it is function that act as a reducer which has two parameter : state and action

-> **useDispatch from react-redux lib** : act as a event dispatcher for the actions.

-> **useSelector from react-redux lib**: use to select the value from the redux store.

- However this all methods are just for the basic information about how the redux architecture work in actuall. But in practical we use the **_Redux toolkit_** which makes our work easy and simpler.

- You may find the practical counter example in the given github link in the folder react-basics: [link](https://github.com/jemmyasjd/React_Redux)

- Run the following command to execute the code : 

```
git clone https://github.com/jemmyasjd/React_Redux
cd react-basics
npm i 
npm run dev
```

-----------------------------------------

## **Redux toolkit Methods:**

-> **configureStore**: use to create the redux store using redux toolkit.

-> **createSlice** : In redux toolkit we make the reducer using the concept of sicer. this method is used to create the slice. Which take name,initital state and reducer as a object parameter. In reducer we make the methods which take state and action as a input to change the state based on the action. 

-> **createSelector** : use to create the selector for easy convinence 

-> **useDispatch** : in redux toolkit we dont need to mention explicitely we just directly pass action from the slice as a parameter.

-> **useSelector from react-redux lib**: use to select the value from the redux store.

-> **action.payload** : it contains change what we had done through dispatcher.

-------------------------------------

## **Practical Add to Cart Example:**

- Firstly we create a store using **_configureStore_** method, in that we pass the reducer which is also consider as a slicer 


![store](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kiy4l1axzb882xw6dk9l.png)

- We Create the cart reducer using **_createSlice_** method

![reducer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qbi8x41qdyz96p6d6dd.png)

- Then we dispatch the event using **_useDispatch_** method 


![dispatcher](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7irloxs39vpx980mpe8j.png)

- Finally we get the data from the store using **_useSelector_** 


![selector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4nrc782ysy747hhxn4g.png)

- **OUTPUT**

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zrayb8wvcfa1fb4b3uwq.png)

- Get the source code : [click here](https://github.com/jemmyasjd/React_Redux)

- Run the following command to execute the code : 

```
git clone https://github.com/jemmyasjd/React_Redux
cd React Toolkit Code
npm i 
npm start
```

------------------

## **Api calling methods:**

-> **createasyncThunk** : used to create the action of fetching the data which take ("name", callback function) which trigger when action dispatch. 

-> Addtionally we have 

    extraReducers: (builder) => {
    builder.addCase(fetchTodos.pending, (state, action) => {
      state.isLoading = true;
    });
    builder.addCase(fetchTodos.fulfilled, (state, action) => {
      state.isLoading = false;
      state.data = action.payload;
    });
    builder.addCase(fetchTodos.rejected, (state, action) => {
      console.log("Error", action.payload);
      state.isError = true;
    });
  
-------------------------------

## **Practical todo fetching example:**

- fetch the todos using **_createThunk_** method


![thunk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f34dcv6i3cvumwvagvzz.png)

- Get code [here](https://github.com/jemmyasjd/React_Redux)

----------------------------------
    
## Conclusion

This blog explored how Redux simplifies state management in large-scale React applications by centralizing state in the Redux Store, eliminating prop drilling, and promoting consistency. The architecture of actions, dispatchers, reducers, and subscriptions enhances maintainability. The Redux Toolkit further streamlines workflows by reducing boilerplate. Practical examples, like "Add to Cart" and API handling with `createAsyncThunk`, showcase Redux's capabilities. These tools enable developers to build scalable and maintainable React applications, making Redux essential in modern web development. For a deeper understanding, the provided GitHub repository offers practical implementations.