How to manage global state in a React application?
Last Updated :
24 Apr, 2025
Global state refers to data that is accessible across multiple components in a React application. Unlike the local state, which is confined to a single component, the global state can be accessed and modified from anywhere in the component tree.
In this article, we will explore the following approaches by which we can manage the global state in React.
Steps to Create React application and manage global state:
For React Context API: No additional installation is required, as it's built into React.
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Step 3: After setting up the React environment on your system, we can start by creating an App.js file and creating a directory by the name of components.
At last, we can apply any Approach to handle Global State
Folder Structure:
Folder StructurApproach 1: Using Redux
Include dependency in project:
npm install redux react-redux
The updated dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"web-vitals": "^2.1.4"
}
Example: This example implements the above-mentioned approach.
JavaScript
// App.js
import React, { useState } from 'react';
import { Provider } from 'react-redux';
import globalStateStore from './GlobalStateStore';
import GlobalStateDisplay from './GlobalStateDisplay';
const App = () => {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const updateGlobalState = () => {
const number = parseInt(inputValue);
if (!isNaN(number)) {
store.dispatch(
{ type: 'SET_COUNT', payload: number }
);
}
};
return (
<Provider store={store}>
<div>
<input type="number" value={inputValue}
onChange={handleInputChange} />
<button onClick={updateGlobalState}>
Update Global State</button>
<GlobalStateDisplay />
</div>
</Provider>
);
}
export default App;
JavaScript
// GlobalStateDisplay.js
import React from 'react';
import { useSelector } from 'react-redux';
const GlobalStateDisplay = () => {
const count = useSelector(state => state.count);
const squaredValue = count ** 2;
return (
<div>
<p>Global State: {count}</p>
<p>Square of Global State:
{squaredValue}</p>
</div>
);
}
export default GlobalStateDisplay;
JavaScript
//GlobalStateStore.js;
import { createStore } from 'redux';
const initialState = {
count: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'SET_COUNT':
return { ...state, count: action.payload };
default:
return state;
}
};
const GlobalStateStore = createStore(reducer);
export default GlobalStateStore;