0% found this document useful (0 votes)
3 views33 pages

Unit 5

Redux is a state management library for JavaScript applications that helps maintain a predictable state through a single global object called Store. It simplifies data flow and debugging by enforcing unidirectional data flow and using actions, reducers, and the store to manage state changes. The document provides installation instructions, implementation steps for a React-Redux application, and details about Redux DevTools for debugging.

Uploaded by

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

Unit 5

Redux is a state management library for JavaScript applications that helps maintain a predictable state through a single global object called Store. It simplifies data flow and debugging by enforcing unidirectional data flow and using actions, reducers, and the store to manage state changes. The document provides installation instructions, implementation steps for a React-Redux application, and details about Redux DevTools for debugging.

Uploaded by

Uma Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit – 5 Redux:

https://redux.js.org/introduction/getting-
started#:~:text=The%20recommended%20way%20to
%20start,using%20Next's%20with%2Dredux%20template.

Link for Revision

 Redux is a predictable state container for JavaScript apps.


 As the application grows, it becomes difficult to keep it organized and
maintain data flow.
 Redux solves this problem by managing application’s state with a single
global object called Store.
 Redux fundamental principles help in maintaining consistency
throughout your application, which makes debugging and testing easier.

Redux – Installation
Before installing Redux, we have to install Nodejs and NPM. Below are the instructions that
will help you install it. You can skip these steps if you already have Nodejs and NPM installed
in your device.

1. Run the following command in your command prompt to install Redux.


npm install --save redux

2. To use Redux with react application, you need to install an additional dependency
as follows −
npm install --save react-redux

3. To install developer tools To install redux, you can follow the below steps −
for Redux, you need to install the following as dependency −
Run the below command in your command prompt to install Redux dev-tools.
npm install --save-dev redux-devtools
npm install --save-dev redux-devtools --legacy-peer-deps
A Dev Tool (Developer Tool) is a software or library that helps developers debug, inspect,
and optimize their applications. In the case of Redux DevTools, it is a tool for debugging
Redux state management in React applications.
What is Redux DevTools?
Redux DevTools is a development tool that allows you to:
 View state changes in real-time
 Time travel debugging (jump to previous states)
 Track dispatched actions and their effects on the store
 Inspect & revert changes to debug issues faster

Steps To Implement React-Redux1


Step 1: Setting Up the Project
First, create a new React app using create-react-app:
npx create-react-app react-redux-counter
cd react-redux-counter
Next, install redux and react-redux:
npm install redux react-redux

Folder Structure

Dependencies
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"web-vitals": "^2.1.4"
}

Step 2: Create the Redux Slice (counterSlice.js)


In the src/redux/ folder, create a file called counterSlice.js. This will define the actions and
reducer for the counter.
// src/redux/counterSlice.js

const initialState = {
count: 0,
};

// Reducer function that updates the state based on actions


export default function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
}

// Action creators
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });

Step 3: Create the Redux Store (store.js)


Now, create the Redux store in the src/redux/store.js file:
// src/redux/store.js

import { createStore } from 'redux';


import counterReducer from './counterSlice';
// Create a Redux store holding the state of the counter
const store = createStore(counterReducer);

export default store;

Step 4: Create the Counter Component (Counter.js)


Now, create a simple Counter component in the src/components/Counter.js file. This
component will access the state and dispatch actions to increment or decrement the count.
// src/components/Counter.js

import React from 'react';


import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '../redux/counterSlice';

const Counter = () => {


// Access the count value from the Redux store
const count = useSelector((state) => state.count);
// Get the dispatch function from Redux
const dispatch = useDispatch();

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
};

export default Counter;

Step 5: Connect Redux to React


Next, wrap your App component in a Redux Provider so that the store is available
throughout the app.

1.CSS
/* src/index.css */

body {
font-family: Arial, sans-serif;
text-align: center;
}

button {
margin: 5px;
padding: 10px;
font-size: 16px;
}

2.JAVASCRIPT
// src/index.js

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

3. JAVASCRIPTS
// src/App.js

import React from 'react';


import Counter from './components/Counter';

function App() {
return (
<div className="App">
<h1>React-Redux Counter App</h1>
<Counter />
</div>
);
}

export default App;

To start the application run the following command.


npm start
Redux - Data Flow
Redux follows the unidirectional data flow. It means that your application data
will follow in one-way binding data flow. As the application grows & becomes
complex, it is hard to reproduce issues and add new features if you have no
control over the state of your application.
Redux reduces the complexity of the code, by enforcing the restriction on how
and when state update can happen. This way, managing updated states is
easy. We already know about the restrictions as the three principles of Redux.
Following diagram will help you understand Redux data flow better –
 An action is dispatched when a user interacts with the application.
 The root reducer function is called with the current state and the dispatched action.
The root reducer may divide the task among smaller reducer functions, which
ultimately returns a new state.
 The store notifies the view by executing their callback functions.
 The view can retrieve updated state and re-render again.

store in Redux
Redux is the state management library that is used in JavaScript apps. It is used
to manage the state of data and access them at different components level in
the app. In redux, there are three parts as follows:
 Actions
 Reducer
 Store
Prerequisites
 React State Management
 Basics of Redux
 Understanding Flux Architecture
Store: It is an object which provides the state of the application. This object is
accessible with help of the provider in the files of the project. The only way to
change the state inside it is to dispatch an action on it.
There are three important parts of the store:
 createStore(): To create a store object in redux.
 dispatch(action): To change the state of store data by using the actions.
 getState(): For getting the current state of the store in redux.
Stesps to create React Application & Install Redux
Step 1: Create a React application using the following command:
npx create-react-app example
Step 2: After creating your project folder i.e. example, move to it using the
following command:
cd example
Step 3: Install the following modules. From the root directory of your project in
the terminal, run the following command:
npm install redux
npm install react-redux
Project Structure:

Example: Let’s make a simple counter application with help of redux to


understand the store.
// index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import appStore from "./redux/store";

ReactDOM.render(
<React.StrictMode>
<Provider store={appStore}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);

// App.js
import "./App.css";
import Counter from "./components/counter";

function App() {
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: "100vh",
}}
>
<Counter />
</div>
);
}

export default App;

// Counter.jsx

import React from "react";


import { connect } from "react-redux";
import {
incrementCount,
decrementCount,
} from "../redux/actions/counterActions";

class Counter extends React.Component {


render() {
const { count, incrementCount, decrementCount } =
this.props;
return (
<div>
<button onClick={() => decrementCount()}>-
</button>
<span> {count} </span>
<button onClick={() =>
incrementCount()}>+</button>
</div>
);
}
}

const mapStateToProps = (state) => ({


count: state,
});
const mapDispatchToProps = (dispatch) => ({
decrementCount: () => dispatch(decrementCount()),
incrementCount: () => dispatch(incrementCount()),
});

export default connect(mapStateToProps, mapDispatchToProps)


(Counter);

//actions/counterActions.jsx

const INCREMENT = "INCREMENT";


const DECREMENT = "DECREMENT";

const incrementCount = () => ({


type: INCREMENT,
});

const decrementCount = () => {


return {
type: DECREMENT,
};
};

export { INCREMENT, incrementCount, decrementCount,


DECREMENT };

//reducer/currencyReducer.jsx
import { INCREMENT, DECREMENT } from
"../actions/counterActions";

const currencyReducer = (state = 0, action) => {


switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};

export { currencyReducer };

Step to run the application: Run the application using the following
command:
npm start

Reducers in Redux
In Redux, reducers are pure functions that handle state logic,
accepting the initial state and action type to update and
return the state, facilitating changes in React view
components.
(State,action) => newState
This was about the reducer syntax and its definition.
Now we will discuss the term pure function that we have
used before.
Pure function
A function is said to be pure if the return value is determined
by its input values only and the return value is always the
same for the same input values or arguments. A pure
function has no side effects.

Pure Function Example:


Below is an example of a pure function:

const multiply= (x, y) => x * y;


multiply(5,3);
In the above example, the return value of the function is
based on the inputs, if we pass 5 and 3 then we’d always get
15, as long as the value of the inputs is the same,
the output will not get affected.
Redux Reducer Syntax:
Here is an example of a reducer function that takes state and
action as parameters.
const initialState = {};
const Reducer = (state = initialState, action) => {
// Write your code here
}
Redux Reducer Parameters:
 Redux State

 Redux Action

Redux State
The reducer function contains two parameters one of them is
the state. The State is an object that holds some information
that may change over the lifetime of the component. If the
state of the object changes, the component has to re-render.
In redux, Updation of state happens in the reducer function.
Basically reducer function returns a new state by performing
an action on the initial state. Below, is an example of how we
can declare the initial state of an application.
Redux State Syntax:
const INITIAL_STATE = {
userID: '',
name: '',
courses: []
}
Redux Actions
The second parameter of the reducer function is actions.
Actions are JavaScript object that contains information.
Actions are the only source of information for the store. The
Actions object must include the type property and it can also
contain the payload(data field in the actions) to describe the
action.
Redux Action Syntax:
For example, an educational application might have this
action:
{
type: 'CHANGE_USERNAME',
username: 'GEEKSFORGEEKS'
}
{
type: 'ADD_COURSE',
payload: ['Java with geeksforgeeks',
'Web Development with GFG']
}
Redux Reducer Working Example:
We have created two buttons one will increment the value by
2 and another will decrement the value by 2 but, if the value
is 0, it will not get decremented we can only increment it.
With Redux, we are managing the state state-managing

// Filename - App.js

import React from 'react';


import './index.css';
import { useSelector, useDispatch } from 'react-redux';
import { incNum, decNum } from './actions/index';
function App() {
const mystate = useSelector((state) => state.change);
const dispatch = useDispatch();
return (
<>
<h2>Increment/Decrement the number by 2,
using Redux.</h2>
<div className="app">

<h1>{mystate}</h1>
<button onClick={() => dispatch(incNum())}>
+</button>
<button onClick={() => dispatch(decNum())}>
-</button>
</div>
</>
);
}
export default App;

//src/index.js

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App.jsx'
import store from './store';
import { Provider } from 'react-redux';

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById("root")
);

//index.js

export const incNum = () => {


return { type: "INCREMENT" }
}
export const decNum = () => {
return { type: "DECREMENT" }
}

//reducers/func.js
const initialState = 0;
const change = (state = initialState, action) => {
switch (action.type) {
case "INCREMENT": return state + 2;
case "DECREMENT":
if (state == 0) {
return state;
}
else {
return state - 2;
}
default: return state;
}
}
export default change;

//reducer/index.js

import change from './func'


import { combineReducers } from 'redux';
const rootReducer = combineReducers({
change
});

export default rootReducer;

//store.js

import { createStore } from 'redux';


import rootReducer from './reducers/index';
const store = createStore(rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;

Connecting Components
In Redux, components connect to the store using the useSelector and
useDispatch hooks (in modern React with Redux Toolkit) or the connect
function (in older class-based components). Here's how you can connect
components in Redux:
Using Hooks (useSelector & useDispatch)
This is the recommended way for function components.
1. Setting Up Redux Store
Ensure your Redux store is set up using configureStore from Redux Toolkit:
javascript
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

const store = configureStore({


reducer: {
counter: counterReducer,
},
});

export default store;


2. Connecting Components
 Access State: Use useSelector to get data from the Redux store.
 Dispatch Actions: Use useDispatch to send actions.
javascript
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';

const Counter = () => {


const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
};

export default Counter;

Using connect (Class Components - Older Method)


For class components, you can use the connect function from react-redux.
javascript

import { connect } from 'react-redux';


import { increment, decrement } from './counterSlice';
const Counter = ({ count, increment, decrement }) => {
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
};

const mapStateToProps = (state) => ({


count: state.counter.value,
});

const mapDispatchToProps = {
increment,
decrement,
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

Wrapping with Provider


To make Redux available in the component tree, wrap your app with <Provider
store={store}> in index.js:
javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Dispatching Actions in Redux
In Redux, actions are dispatched to update the state. You can
dispatch actions using either useDispatch (for functional
components) or connect (for class components). Below is a detailed
explanation of both methods.

1. Using useDispatch (Modern React with Redux Hooks)


This method is used in functional components.
Steps to Dispatch Actions in a Functional Component
1. Setup Redux Store and Slice (Using Redux Toolkit)
First, create a slice with action creators:
javascript
// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({


name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});

export const { increment, decrement, incrementByAmount } =


counterSlice.actions;
export default counterSlice.reducer;
2. Configure Store
javascript
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

const store = configureStore({


reducer: {
counter: counterReducer,
},
});

export default store;


3. Dispatch Actions in a Functional Component
javascript

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


import { increment, decrement, incrementByAmount } from
'./counterSlice';

const Counter = () => {


const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
<button onClick={() =>
dispatch(incrementByAmount(5))}>+5</button>
</div>
);
};
export default Counter;

2. Using connect (Older Class-Based Components)


If you are using class components, you dispatch actions using
connect from react-redux.
javascript
import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement, incrementByAmount } from
'./counterSlice';

const Counter = ({ count, increment, decrement,


incrementByAmount }) => {
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={() => incrementByAmount(5)}>+5</button>
</div>
);
};

// Map state and actions to props


const mapStateToProps = (state) => ({
count: state.counter.value,
});

const mapDispatchToProps = {
increment,
decrement,
incrementByAmount,
};

// Connect component to Redux


export default connect(mapStateToProps, mapDispatchToProps)
(Counter);

3. Dispatching Async Actions (Thunk)


To handle API calls, Redux uses redux-thunk. Here’s how you can
dispatch asynchronous actions:
1. Create an Async Thunk
javascript
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

// Async action
export const fetchData = createAsyncThunk('counter/fetchData',
async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data.value;
});

const counterSlice = createSlice({


name: 'counter',
initialState: { value: 0, status: 'idle' },
reducers: {
increment: (state) => {
state.value += 1;
},
},
extraReducers: (builder) => {
builder
.addCase(fetchData.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchData.fulfilled, (state, action) => {
state.value = action.payload;
state.status = 'success';
})
.addCase(fetchData.rejected, (state) => {
state.status = 'failed';
});
},
});

export const { increment } = counterSlice.actions;


export default counterSlice.reducer;

2. Dispatch Async Action in Component


javascript
import { useSelector, useDispatch } from 'react-redux';
import { fetchData } from './counterSlice';

const Counter = () => {


const count = useSelector((state) => state.counter.value);
const status = useSelector((state) => state.counter.status);
const dispatch = useDispatch();

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(fetchData())}>
{status === 'loading' ? 'Loading...' : 'Fetch Data'}
</button>
</div>
);
};

export default Counter;

How to work on it
1. Set Up a React Project with Redux Toolkit
If you haven't already created a React project, you need to set it up first.
Create a React App (if not already created)
Open your terminal and run:
bash

npx create-react-app my-redux-app


cd my-redux-app
Install Dependencies
Install react-redux and @reduxjs/toolkit:
bash

npm install @reduxjs/toolkit react-redux

2. Set Up Redux Store


Create a store.js file inside the src folder:
javascript

// src/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

const store = configureStore({


reducer: {
counter: counterReducer,
},
});

export default store;

3. Create a Redux Slice


Create a counterSlice.js file inside the src folder:
javascript

// src/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({


name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;


export default counterSlice.reducer;

4. Connect Redux to the App


Modify index.js to wrap your app with the Redux Provider:
javascript

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

5. Create a Counter Component


Modify App.js to use Redux actions:
javascript

// src/App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';

const App = () => {


const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();

return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
<button onClick={() => dispatch(incrementByAmount(5))}>+5</button>
</div>
);
};

export default App;


6. Run the Project
After setting everything up, start the React app:
bash
npm start
This will open a browser window at http://localhost:3000/, and you should see the counter
working.

Debugging and Deployment:


Debugging
 The process of finding and fixing errors in software
 Also known as finding and resolving bugs
 Helps improve software performance and prevent issues
Deployment
 The process of making software available for use
 Can be done in debug mode or normal mode

Debugging react app


1. Enable Debugging in VS Code
VS Code has a built-in JavaScript debugger that works well with React.
Step 1: Open VS Code and Your React Project
Make sure you have a React project open in VS Code.

npx create-react-app my-app


cd my-app

2. Run the React App in Debug Mode


Before debugging, start your React app in development mode.

npm start
or

yarn start
This will open the React app in the browser (http://localhost:3000).

3. Add Debugging Configuration


1. Open VS Code and go to the Run and Debug panel (Ctrl + Shift + D).
2. Click on "create a launch.json file".
3. Select "Chrome" as the environment.
4. Modify the launch.json file as follows:
json
CopyEdit
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome for React",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
Explanation of launch.json
 type: "chrome" → Launches Chrome.
 url: "http://localhost:3000" → React development server.
 webRoot: "${workspaceFolder}/src" → Maps to React's src folder.

Building the app


Step 1: Set Up a React App
We’ll begin by creating a new React app using Create React App. Open your terminal and
execute the following commands:
npx create-react-app redux-counter-app
cd redux-counter-app
Here, create-react-app is a tool that sets up a new React project with a pre-configured
development environment.
Step 2: Install Redux and React-Redux
Next, install the necessary dependencies for Redux and React-Redux:
npm install redux react-redux
Redux serves as the core library for state management, while React-Redux provides the
official bindings that allow React components to interact with the Redux store.
Step 3: Update the App Component
Open src/App.js and replace its content with the following code:
// src/App.js
import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from './actions';
function App({ count, increment, decrement }) {
return (
<div className="App">
<h1>Redux Counter App</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
const mapStateToProps = (state) => {
return {
count: state.count,
};
};
const mapDispatchToProps = {
increment,
decrement,
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
In this step, we define the main App component and connect it to the Redux store using
the connect function from React-Redux.
Key Concepts:
 connect: A function provided by React-Redux that connects a React component to
the Redux store, enabling the component to subscribe to store updates and dispatch
actions.
 mapStateToProps: A function that maps the Redux state to the component props. It
defines which part of the Redux state is exposed to the component.
 mapDispatchToProps: An object or function that maps action creators to the
component props. It simplifies the process of dispatching actions from the
component.
Step 4: Create Actions
Create a new folder named actions inside the src folder, and add a file named index.js with
the following content:
// src/actions/index.js
export const increment = () => {
return {
type: 'INCREMENT',
};
};
export const decrement = () => {
return {
type: 'DECREMENT',
};
};
Actions in Redux are plain JavaScript objects that describe changes in the application state.
In our example, we define increment and decrement actions to modify the counter.
Step 5: Create Reducers
Create a new folder named reducers inside the src folder, and add a file named index.js with
the following content:
// src/reducers/index.js
const initialState = {
count: 0,
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1,
};
case 'DECREMENT':
return {
count: state.count - 1,
};
default:
return state;
}
};
export default counterReducer;
Reducers are functions that specify how the application state changes in response to
actions. The counterReducer takes the current state and an action and returns a new state
based on the action type.
Key Concept:
 Reducers: Functions that handle state changes in a Redux application. They take the
current state and an action as arguments and return a new state.
Step 6: Create a Redux Store
Open src/index.js and modify it as follows:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import counterReducer from './reducers';
const store = createStore(counterReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
In this step, we create the Redux store using createStore from Redux.
The Provider component from React-Redux wraps the entire application, making the store
accessible to all components.
Key Concepts:
 createStore: A function from Redux that creates a Redux store to hold the complete
state tree of the application.
 Provider: A React component that makes the Redux store available to the entire
React application.

Step 7: Start Development Server


Start your development server by running:

npm start

This command initiates the development server, and you


can view your app at http://localhost:3000.

Best practices for its


build & deployment process
Setting Up a New React Redux Project
To set up a new React Redux project, you'll need to install the required dependencies.
Create a new project folder and navigate to it in your terminal.
Install React and Redux
Run the following command to install React and Redux:
npx create-react-app my-app --template redux
This command creates a new React project with Redux installed.
Install Additional Dependencies
Install the following dependencies:
npm install react-redux redux-devtools-extension
Project Structure
The project structure for a React Redux project typically includes the following folders:
 actions: Holds action creators that trigger state changes.
 components: Holds React components that make up the user interface.
 containers: Holds higher-order components that connect to the Redux store.
 reducers: Holds reducers that handle state changes.
 store: Holds the Redux store configuration.
Creating Actions
Actions are payloads that trigger state changes in your application. Create a new
file actions/index.js and add the following code:
export const increment = () => {
return {
type: 'INCREMENT',
};
};
export const decrement = () => {
return {
type: 'DECREMENT',
};
};
These actions trigger state changes in your application.
Creating Reducers
Reducers handle state changes by taking the current state and an action, and returning a
new state. Create a new file reducers/index.js and add the following code:
const initialState = {
count: 0,
};

const reducer = (state = initialState, action) => {


switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

export default reducer;


This reducer handles the INCREMENT and DECREMENT actions by updating the count state.
Creating the Store
Create a new file store/index.js and add the following code:
import { createStore, combineReducers } from 'redux';
import reducer from '../reducers';

const store = createStore(combineReducers({ reducer }));

export default store;


This code creates a new Redux store using the reducer function.
Connecting Components to the Store
Create a new file containers/Counter.js and add the following code:
import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from '../actions';

const Counter = ({ count, increment, decrement }) => {


return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
};

const mapStateToProps = state => {


return { count: state.count };
};

const mapDispatchToProps = dispatch => {


return {
increment: () => dispatch(increment()),
decrement: () => dispatch(decrement()),
};
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter);


This code connects the Counter component to the Redux store using the connect function
from react-redux.
Rendering the Component
Create a new file App.js and add the following code:
import React from 'react';
import Counter from './containers/Counter';

const App = () => {


return (
<div>
<Counter />
</div>
);
};

export default App;


This code renders the Counter component.
Conclusion
In this article, we've explored how to build a scalable React Redux project from scratch.
We've covered setting up a new project, creating actions, reducers, and the store, and
connecting components to the store. By following these steps, you can build a robust and
maintainable React Redux project.
Best Practices
 Keep your actions, reducers, and store configuration organized and separate.
 Use the connect function from react-redux to connect components to the store.
 Use the mapStateToProps and mapDispatchToProps functions to connect
components to the store.
 Use the Redux DevTools extension to debug your application.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy