React Redux Toolkit
Published: 2024-06-27 19:24:54

Problem Statement
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zfm805o4rw509tbfwgs.png)

When working with React, you typically engage in larger projects. Otherwise, HTML and CSS suffice for simpler development needs. A substantial project involves numerous components and elements, as seen in an ecommerce website. Synchronizing these components—such as updating the cart and total upon clicking "Add to Cart"—can pose challenges.

Without a redux this is how we implement this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mctvj7q1w0oi4p22bqr4.png)
We are doing prop drilling here.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xjprc69zl5kd2lr3eykq.png)
Here, we observe tight coupling because each component relies on its parent to access state. The solution lies in implementing a single source of truth.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bxprztirdxlohb79681.png)
The concept of a "single source of truth" dictates that state components should not reside in the app component but rather in a centralized store accessible to any component. The cart subscribes to this store, ensuring that any changes trigger its re-rendering. On the product page, when an item is added, it updates the store, prompting the cart to re-render in response to these changes.

Architecture of Redux 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6ihi2goqrmqljnk8u73.png)
React Redux is a popular library combination used in React applications to manage state and facilitate data flow. Here's a breakdown of its architecture:

1. With the UI handler button clicked.
2. From button goes to handler function and handler function dispatch event.
3. Event goes to store(store does know what to do with event).
4. Store give event to reducer with the current value of the state.
5. Reducer will do the changes on the current value based on the event.
6. Reducer return the new value to redux store.
7. Redux Store will accept that new value.
8. And those components who are listing that value or subscribed that will get update.

<h4>Install Redux Toolkit and React-Redux</h4>

Add the Redux Toolkit and React-Redux packages to your project:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzen7l7k7mo6mmktoq8f.png)

<h4>Create a Redux Store</h4>
Create store.ts file inside store folder

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uskqs8inxnx1p0uw79ce.png)

1. `export const store = configureStore({ ... });`: Calls the configureStore function to create a Redux store instance. It accepts an object with configuration options.

2. `reducer`: An object that specifies how different slices of the application's state should be combined. In this case, the counterSlice is assigned to the cart key. This means that the counterSlice will manage the state stored under the cart slice of the Redux store.

The provided code sets up a Redux store using @reduxjs/toolkit's configureStore function. It configures the store to use a counterSlice to manage the state related to the cart. Finally, it exports the configured store instance so that it can be imported and used throughout the application to manage and access application state.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hd97ji01akf8x36bclsm.png)
 It renders the App component wrapped in <Provider> to provide access to the Redux store. The use of `ReactDOM.createRoot` and `root.render(...)` indicates the usage of React Concurrent Mode, allowing for more predictable rendering and performance optimizations in modern React applications.

Now, we will make slices
Every feature is a slice, a Redux state slice represents a modular, encapsulated part of the application state managed by Redux. It helps organize and manage state in a more structured and maintainable manner, particularly in larger applications with complex state requirements.

We will create a folder slices inside redux folder and inside slices folder create counter folder and the we will create counter.ts file inside that.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zahu2vcxg7bzo6qpbqdf.png)

- initialState = 0: Specifies the initial state of the application, which is set to 0.
- The reducer handles different action types (INCREMENT and DECREMENT) by returning a new state based on the current state and the action type. If the action type does not match any case (default), it returns the current state unchanged.

The line `export const { increment, decrement, incrementByAmount } = counterSlice.actions` simplifies the process of creating and exporting action creators from a Redux slice defined using Redux Toolkit's createSlice. It promotes cleaner and more concise Redux-related code by automatically generating these action creators based on defined reducers.

Now create hooks inside index.ts which will create in a new folder created called hooks folder in redux folder.

useDispatch and useSelector are React Redux hooks used for interacting with the Redux store in functional components.
useDispatch: Hook used to obtain a reference to the Redux dispatch function, which is used to dispatch actions to the Redux store.
useSelector: Hook used to extract and return data from the Redux store state. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2kalu6sltb698f04u8d4.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20arsvw1m1klq68gte16.png)
we can do this with simple state then why we do this complex so let me show you why create `MyComp.ts` in src

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xuggu0sez8f8flbpevng.png)
So, here we create some dummy component.

Then render my component there

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6n0bqi3xhitd8qg5x0b.png)

So here when we increment one component other also render because this MyComp is also using state means there components subscribed store
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0xvne35rphxm53a6e3w.png)