REACT

Data Flow


Flux is an architectural pattern used for building client-side web applications. It is a state management pattern used in JavaScript applications, particularly with React, to manage data flow in a unidirectional manner. It consists of four main components: actions, dispatcher, stores, and views. This structure ensures a predictable and maintainable data flow.

 

Flux introduces four main parts:


     1. Actions
     2. Dispatcher
     3. Stores
     4. Views (React Components)

 

1. Actions

Actions are payloads of information that send data from the application to the dispatcher. They are typically triggered by user interactions, such as button clicks or form submissions.

// Action Types
const ActionTypes = {
 ADD_TODO: 'ADD_TODO',
};
// Action Creators
const Actions = {
 addTodo: (text) => {
   return {
     type: ActionTypes.ADD_TODO,
     payload: { text },
   };
 },
};
// Example usage
Actions.addTodo('Learn Flux');

 

2. Dispatcher

The dispatcher is a central hub that manages all the data flow in a Flux application. It receives actions and dispatches them to the stores. Each store registers with the dispatcher and provides a callback that the dispatcher invokes with each action.

import { Dispatcher } from 'flux';
const AppDispatcher = new Dispatcher();
// Register a callback with the dispatcher
AppDispatcher.register((action) => {
 switch (action.type) {
   case ActionTypes.ADD_TODO:
     // Handle the action in the store
     TodoStore.addTodo(action.payload.text);
     break;
   // Other cases
 }
});
// Dispatch an action
AppDispatcher.dispatch(Actions.addTodo('Learn Flux'));

 

3. Stores

Stores hold the application state and logic. They respond to actions sent by the dispatcher and emit change events to notify views of the updates. Stores are similar to models in traditional MVC, but they manage the state for a specific domain of the application.

import { EventEmitter } from 'events';
class TodoStore extends EventEmitter {
 constructor() {
   super();
   this.todos = [];
 }
 addTodo = (text) => {
   this.todos.push({ text });
   this.emit('change');
 };
 getTodos = () => {
   return this.todos;
 }
 // Register with the dispatcher
 handleActions = (action) => {
   switch (action.type) {
     case ActionTypes.ADD_TODO:
       this.addTodo(action.payload.text);
       break;
     // Other cases
   }
 }
}
const todoStore = new TodoStore();
AppDispatcher.register(todoStore.handleActions.bind(todoStore));
export default todoStore;

 

4. Views (React Components)

Views are React components that render the UI based on the state from the stores. They listen for change events from the stores and re-render when the state changes.

import React, { Component } from 'react';
import todoStore from './TodoStore';
class TodoApp extends Component {
 constructor(props) {
   super(props);
   this.state = {
     todos: todoStore.getTodos(),
   };
 }
 componentDidMount() {
   todoStore.on('change', this.updateTodos);
 }
 componentWillUnmount() {
   todoStore.removeListener('change', this.updateTodos);
 }
 updateTodos = () => {
   this.setState({ todos: todoStore.getTodos() });
 };
 render() {
   return (
     <div>
       <ul>
         {this.state.todos.map((todo, index) => (
           <li key={index}>{todo.text}</li>
         ))}
       </ul>
     </div>
   );
 }
}
export default TodoApp;

 

Data Flow in Flux

     1. User Interaction: The user interacts with the UI, such as clicking a button or submitting a form.
     2. Action Creation: The interaction triggers an action. The action creator function creates an action object.
     3. Dispatching: The action object is sent to the dispatcher.
     4. Dispatcher: The dispatcher dispatches the action to all registered callbacks.
    5. Stores: Each store receives the action and updates its state accordingly. After updating the state, the store emits a change event.
    6. Views: React components listen for change events from the stores. When a change event is detected, the components retrieve the new state from the stores and re-render the UI.

 

Advantages of Flux

 

     • Predictable State Changes: Unidirectional data flow makes it easier to understand how data changes in the application.
         • Decoupled Components: Stores and views are decoupled, which promotes modularity and reusability.
         • Centralized Dispatcher: The dispatcher acts as a central hub, making it easier to manage and debug the flow of data.