Unit 5
Unit 5
https://redux.js.org/introduction/getting-
started#:~:text=The%20recommended%20way%20to
%20start,using%20Next's%20with%2Dredux%20template.
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.
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
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"
}
const initialState = {
count: 0,
};
// Action creators
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
};
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
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
3. JAVASCRIPTS
// src/App.js
function App() {
return (
<div className="App">
<h1>React-Redux Counter App</h1>
<Counter />
</div>
);
}
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:
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>
);
}
// Counter.jsx
//actions/counterActions.jsx
//reducer/currencyReducer.jsx
import { INCREMENT, DECREMENT } from
"../actions/counterActions";
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.
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
<h1>{mystate}</h1>
<button onClick={() => dispatch(incNum())}>
+</button>
<button onClick={() => dispatch(decNum())}>
-</button>
</div>
</>
);
}
export default App;
//src/index.js
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById("root")
);
//index.js
//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
//store.js
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';
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
};
const mapDispatchToProps = {
increment,
decrement,
};
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.
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;
const mapDispatchToProps = {
increment,
decrement,
incrementByAmount,
};
// 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;
});
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(fetchData())}>
{status === 'loading' ? 'Loading...' : 'Fetch Data'}
</button>
</div>
);
};
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
// src/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
// src/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
// 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')
);
// src/App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';
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>
);
};
npm start
or
yarn start
This will open the React app in the browser (http://localhost:3000).
npm start