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.
// 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' }}>
w3wiki
</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.
// 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' }}>
w3wiki
</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/
How to Use Flux to Manage State in ReactJS?
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.
Contact Us