0% found this document useful (0 votes)
4 views9 pages

React Redux

Redux is a state management library that centralizes application state, making it easier to manage complex state interactions in React applications. It operates on principles such as a single source of truth, read-only state, and pure functions for state changes, and integrates with React through the React-Redux library. Redux Toolkit simplifies the setup and usage of Redux, offering features like createSlice for defining reducers and actions together, and RTK Query for efficient data fetching and caching.

Uploaded by

mozzie453
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

React Redux

Redux is a state management library that centralizes application state, making it easier to manage complex state interactions in React applications. It operates on principles such as a single source of truth, read-only state, and pure functions for state changes, and integrates with React through the React-Redux library. Redux Toolkit simplifies the setup and usage of Redux, offering features like createSlice for defining reducers and actions together, and RTK Query for efficient data fetching and caching.

Uploaded by

mozzie453
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

React Redux — Complete and Highly Detailed Notes

1. Introduction

Redux is a predictable state management library that helps manage application state in a
consistent and centralized manner. It is often used with React to simplify state sharing across
components and ensure predictable data flow.

React’s built-in state (useState, useReducer, useContext) is sufficient for small applications, but as
the application grows, managing and synchronizing state across multiple components becomes
complex — this is where Redux is used.

Redux is based on Flux architecture and the principle of unidirectional data flow.

2. Core Principles of Redux

1. Single Source of Truth


The entire state of the application is stored in a single object called the Store.

2. const store = {

3. user: { name: "Harsh", loggedIn: true },

4. products: [],

5. cart: [],

6. };

7. State is Read-Only
The only way to change the state is to dispatch an action, which describes what happened.

8. Changes are Made with Pure Functions (Reducers)


Reducers take the current state and an action, then return a new state — they are pure
functions (no side effects, deterministic).

3. Redux Architecture Flow

┌─────────────┐ ┌───────────┐ ┌────────────┐

│ Component │──────▶│ Action │──────▶│ Reducer │

└─────────────┘ └───────────┘ └────────────┘

▲ │

│ ▼

└────────────── Store (Central State) ◀──────┘

1. Component dispatches an Action.

2. Action is received by the Reducer.


3. Reducer computes the new state.

4. Store updates and notifies components subscribed to it.

5. Components re-render with updated state.

4. Key Concepts and Building Blocks

4.1 Store

• The Store holds the entire application state.

• Created using createStore() or configureStore() (Redux Toolkit).

• Only one store per application.

import { createStore } from "redux";

const store = createStore(reducer);

4.2 Actions

• Actions are plain JavaScript objects describing what happened.

• Must have a type property.

• May include additional payload data.

const addItem = (item) => ({

type: "ADD_ITEM",

payload: item,

});

4.3 Reducers

• Pure functions that define how state changes in response to actions.

• Accept current state and action, return new state.

const cartReducer = (state = [], action) => {

switch ([Link]) {

case "ADD_ITEM":

return [...state, [Link]];

case "REMOVE_ITEM":

return [Link]((item) => [Link] !== [Link]);

default:

return state;

}
};

4.4 Dispatch

• Function that sends an action to the store to update the state.

[Link](addItem({ id: 1, name: "Laptop" }));

4.5 Subscriptions

• Components can subscribe to the store to get updates when state changes.

5. React Integration with Redux

React integrates Redux via the React-Redux library, which provides:

• Provider — connects the Redux store with the React app.

• useSelector — selects state from the store.

• useDispatch — dispatches actions.

Example Setup:

import React from "react";

import ReactDOM from "react-dom";

import { Provider } from "react-redux";

import store from "./store";

import App from "./App";

[Link](

<Provider store={store}>

<App />

</Provider>,

[Link]("root")

);

6. Hooks in React Redux

6.1 useSelector()

• Extracts state from the Redux store.

const cartItems = useSelector((state) => [Link]);

6.2 useDispatch()
• Dispatches actions.

const dispatch = useDispatch();

dispatch(addItem({ id: 1, name: "Laptop" }));

7. Redux Toolkit (RTK)

Redux Toolkit simplifies setup and reduces boilerplate. It includes:

• configureStore for easy store setup.

• createSlice for defining reducers + actions together.

• createAsyncThunk for handling async logic.

Example using createSlice:

import { createSlice, configureStore } from "@reduxjs/toolkit";

const cartSlice = createSlice({

name: "cart",

initialState: [],

reducers: {

addItem: (state, action) => {

[Link]([Link]);

},

removeItem: (state, action) => {

return [Link]((item) => [Link] !== [Link]);

},

},

});

export const { addItem, removeItem } = [Link];

const store = configureStore({

reducer: {

cart: [Link],

},
});

export default store;

8. Async Actions with Redux

Redux by default handles synchronous actions.


To handle async logic (like API calls), middleware is used.

Common Middleware:

• Redux Thunk – allows dispatching functions instead of objects.

• Redux Saga – handles complex async flows using generators.

Example with Thunk:

export const fetchProducts = () => async (dispatch) => {

dispatch({ type: "PRODUCTS_LOADING" });

try {

const res = await fetch("/api/products");

const data = await [Link]();

dispatch({ type: "PRODUCTS_SUCCESS", payload: data });

} catch (err) {

dispatch({ type: "PRODUCTS_ERROR", payload: [Link] });

};

9. Middleware

Middleware intercepts actions between dispatching and reaching reducers.

Example Flow:

Action → Middleware → Reducer → Store → Component

Common uses:

• Logging

• Async API calls

• Error handling

• Authentication checks
Example logging middleware:

const logger = (store) => (next) => (action) => {

[Link]("Dispatching:", action);

const result = next(action);

[Link]("Next State:", [Link]());

return result;

};

10. Redux DevTools

• Allows inspection of actions, state, and time travel debugging.

• Enabled by default in configureStore() from Redux Toolkit.

11. State Normalization

State should be flat and normalized for performance and simplicity.


Example of normalized data:

users: { byId: { 1: { id: 1, name: "A" } }, allIds: [1] }

12. Selector Functions

Selectors abstract away how data is stored in Redux.


They can also memoize derived data using reselect.

import { createSelector } from "reselect";

const selectCartItems = (state) => [Link];

const selectTotalPrice = createSelector([selectCartItems], (items) =>

[Link]((total, item) => total + [Link], 0)

);

13. Best Practices

• Keep reducers pure and side-effect free.


• Never mutate state directly.

• Use Redux Toolkit to minimize boilerplate.

• Keep the store minimal (only necessary global data).

• Co-locate slice logic with features.

• Use TypeScript for type-safe Redux code.

• Memoize expensive selectors.

14. When to Use Redux

Use Redux when:

• The app has complex global state shared by many components.

• You need predictable and debuggable state transitions.

• You require caching, undo/redo, or complex async flows.

Avoid Redux for:

• Simple apps with minimal shared state.

• Components with isolated or local state only.

15. Example: Full Redux Flow

// [Link]

import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({

name: "counter",

initialState: { value: 0 },

reducers: {

increment: (state) => { [Link] += 1; },

decrement: (state) => { [Link] -= 1; },

incrementByAmount: (state, action) => { [Link] += [Link]; },

},

});

export const { increment, decrement, incrementByAmount } = [Link];


export default [Link];

// [Link]

import { configureStore } from "@reduxjs/toolkit";

import counterReducer from "./slice";

export default configureStore({

reducer: { counter: counterReducer },

});

// [Link]

import React from "react";

import { useSelector, useDispatch } from "react-redux";

import { increment, decrement, incrementByAmount } from "./slice";

export default function Counter() {

const count = useSelector((state) => [Link]);

const dispatch = useDispatch();

return (

<div>

<h1>{count}</h1>

<button onClick={() => dispatch(increment())}>+</button>

<button onClick={() => dispatch(decrement())}>-</button>

<button onClick={() => dispatch(incrementByAmount(5))}>+5</button>

</div>

);

16. Redux Toolkit Query (RTK Query)

An advanced addition to Redux Toolkit for data fetching and caching.

Features:

• Auto-caching and invalidation.


• Simplified API calls.

• Optimistic updates.

Example:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const api = createApi({

baseQuery: fetchBaseQuery({ baseUrl: "/api" }),

endpoints: (builder) => ({

getUsers: [Link]({

query: () => "/users",

}),

}),

});

export const { useGetUsersQuery } = api;

You might also like