How to Use Flux to Manage State in ReactJS?
Last Updated :
20 May, 2024
State management in ReactJS is important for building dynamic and responsive applications. Flux, an architecture for managing state, provides a structured approach to handle data flow and state changes efficiently in React applications. In this article, we will explore the Flux to Manage State in ReactJS with proper examples.
Prerequisites:
What is Flux in ReactJS?
Flux is an architectural pattern used for managing state in ReactJS applications. It was introduced by Facebook to address the complexity of state management in large-scale applications. Flux consists of a unidirectional data flow, making it easier to understand and manage the state changes in an application.
Components of Flux
- Dispatcher: The central hub that manages all actions and dispatches them to the appropriate stores. It does not have much logic itself but serves as a mediator between actions and stores.
- Stores: Containers for application state and logic. Each store is responsible for a particular domain of the application. Stores register with the dispatcher to receive actions and update their state accordingly.
- Actions: Objects that contain information about what happened in the application (e.g., user interactions, server responses). Actions are dispatched through the dispatcher to the stores.
- Views (Components): React components that listen to changes in the stores and re-render accordingly. They can also trigger actions in response to user interactions.
Approach to Use Flux to Manage State in ReactJS
To manage the state using flux follow the steps given below
- Define Actions: Create actions that describe state changes.
- Create Dispatcher: Use a central dispatcher to broadcast actions to stores.
- Implement Stores: Develop stores to manage state and respond to actions.
- Update Views: Design React components to render based on store state.
- Subscribe to Changes: Have components subscribe to store updates and re-render on state changes.
- Trigger Actions: Use action creators to dispatch actions from user interactions or other events.
Steps to Setup a React App
Step 1: Create a ReactJS application by using this command.
npx create-react-app myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Install the flux package using the below command:
npm install flux
Project Structure:

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-scripts": "5.0.1",
"flux": "^4.0.4",
"web-vitals": "^2.1.4"
}
Example 1: In this example, we are using Flux to manage state in a simple counter application. The Dispatcher handles actions to increment or decrement the counter, while registered listeners update the component state and re-render the UI.
JavaScript
// App.js
import React, { useEffect, useState } from 'react';
import { Dispatcher } from 'flux';
const dispatcher = new Dispatcher();
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const incrementAction =
() => ({ type: INCREMENT });
const decrementAction =
() => ({ type: DECREMENT });
let counter = 0;
const listeners = [];
const registerListener =
(listener) => listeners.push(listener);
const notifyListeners =
() => listeners.forEach(
(listener) => listener(counter));
dispatcher.register((action) => {
switch (action.type) {
case INCREMENT:
counter += 1;
break;
case DECREMENT:
counter -= 1;
break;
default:
return;
}
notifyListeners();
});
const App = () => {
const [count, setCount] = useState(counter);
useEffect(() => {
registerListener(setCount);
}, []);
const increFn = () => {
dispatcher.dispatch(incrementAction());
};
const decreFn = () => {
dispatcher.dispatch(decrementAction());
};
return (
<div style={{
textAlign: 'center',
marginTop: '50px'
}}>
<h1 style={{ color: 'green' }}>
GeeksforGeeks
</h1>
<h3>Example 1</h3>
<h2 style={{ color: 'blue' }}>
{count}
</h2>
<button
onClick={increFn}
style={{
padding: '10px',
marginRight: '10px',
cursor: 'pointer'
}}>
Increment
</button>
<button
onClick={decreFn}
style={{
padding: '10px',
cursor: 'pointer'
}}>
Decrement
</button>
</div>
);
};
export default App;
Step to Run Application:Â Run the application using the following command from the root directory of the project
npm start
Output:Â Your project will be shown in the URL http://localhost:3000/

Example 2: In this example, we are using Flux to manage the state of a todo list in a React application. The Dispatcher handles actions to add and remove todos, and the state is updated through registered listeners that notify the React component to re-render with the updated todo list.
JavaScript
// App.js
import React, { useEffect, useState } from 'react';
import { Dispatcher } from 'flux';
const dispatcher = new Dispatcher();
const ADD_TODO = 'ADD_TODO';
const REMOVE_TODO = 'REMOVE_TODO';
const addTodoAction =
(todo) => ({ type: ADD_TODO, todo });
const removeTodoAction =
(index) => ({ type: REMOVE_TODO, index });
let todos = [];
const listeners = [];
const registerListener =
(listener) => listeners.push(listener);
const notifyListeners =
() => listeners.forEach(
(listener) => listener(todos));
dispatcher.register((action) => {
switch (action.type) {
case ADD_TODO:
todos.push(action.todo);
break;
case REMOVE_TODO:
todos = todos.filter(
(_, i) => i !== action.index);
break;
default:
return;
}
notifyListeners();
});
const App = () => {
const [todoList, setTodoList] = useState(todos);
const [input, setInput] = useState('');
useEffect(() => {
registerListener(setTodoList);
}, []);
const addFn = () => {
if (input.trim()) {
dispatcher.dispatch(addTodoAction(input));
setInput('');
}
};
const removeFn = (index) => {
dispatcher.dispatch(removeTodoAction(index));
};
return (
<div style={{
textAlign: 'center',
marginTop: '50px'
}}>
<h1 style={{ color: 'green' }}>
GeeksforGeeks
</h1>
<h3>Example 2</h3>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
style={{
padding: '10px',
marginRight: '10px'
}} />
<button
onClick={addFn}
style={{
padding: '10px',
cursor: 'pointer'
}}>
Add Todo
</button>
<ul style={{
listStyleType: 'none',
padding: 0, marginTop: '20px'
}}>
{todoList.map((todo, index) => (
<li
key={index}
style={{
padding: '10px',
borderBottom: '1px solid #ccc',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '300px',
margin: '0 auto',
}}>
{todo}
<button
onClick={() => removeFn(index)}
style={{
cursor: 'pointer',
padding: '5px 10px'
}}>
Remove
</button>
</li>
))}
</ul>
</div>
);
};
export default App;
Step to Run Application:Â Run the application using the following command from the root directory of the project
npm start
Output:Â Your project will be shown in the URL http://localhost:3000/
Similar Reads
How to Update Parent State in ReactJS ?
Updating the parent state in React involves passing a callback function as a prop to the child that triggers the state change and updates the data in the state.Prerequisites:ReactJSReact State and PropsReact Components ApproachTo update parent state in React we will pass a function as a prop to the
3 min read
How to Manage State in Remix?
Managing the state in Remix is one of the basics of making interactive applications. State management in Remix happens both on the client and the server, stitching server-side rendering together with client-side state management. Remix gives flexibility to handle the server-side or client-side state
6 min read
How to lift state two levels up in ReactJS ?
We want to lift the state two levels up such that when an event occurs at the lower level component then it should affect the state two levels up. For example, there are three components X, Y, and Z. X is the parent of Component Y, and Component Y is the parent of Component Z. Prerequisites:NodeJS o
2 min read
How to Work with and Manipulate State in React ?
Working with and Manipulating state in React JS makes the components re-render on the UI by Updating the DOM tree. It makes sure to render the latest information and data on the interface. Prerequisites:NPM & Node.jsReact JSState in React JSReact JS Class componentsReact JS Functional Components
6 min read
How to save new state to local JSON using ReactJS ?
To save data in local storage is a common task while creating a react application to store the user-specific data. We can save new state to local JSON using react in local storage of the browser and access that information anytime later. Prerequisites:React JSNPM & Node.jsJavaScript localStorage
2 min read
How to use rxjs module in ReactJS ?
RXJS stands for Reactive Extensions for JavaScript. This module provides the implementation of observable type to work with reactive programming which is an asynchronous programming paradigm. We can use the following approach in ReactJS to use the rxjs module.Approach: We have used the Rxjs module t
2 min read
How to locally manage component's state in ReactJS ?
Any component in React JS majorly depends on its props and state to manage data. A component's state is private to it and is responsible for governing its behavior throughout its life. A state is nothing but a structure that records any data changes in a react application. It can be used for storing
2 min read
How to manage global state in a React application?
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 approac
7 min read
How to update the State of a component in ReactJS ?
To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content. Prerequisites: NPM & Node.jsReact JSReact StateReact
3 min read
State Management with useState Hook in React
useState is a built-in hook that empowers functional components to manage state directly, eliminating the need for class-based components or external state management libraries for simple use cases. It provides an easy mechanism to track dynamic data within a component, enabling it to React to user
3 min read