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' }}>
                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.

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' }}>
                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.

Prerequisites:

Similar Reads

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...

Steps to Setup a React App

Step 1: Create a ReactJS application by using this command....

Contact Us