Top Related Projects
The library for web and native user interfaces.
A JS library for predictable global state management
🗃️ Centralized State Management for Vue.js.
Simple, scalable state management.
Reactive State for Angular
A reactive programming library for JavaScript
Quick Overview
Flux is an application architecture for building user interfaces, developed by Facebook. It complements React views by utilizing a unidirectional data flow. The Flux pattern is designed to make it easier to reason about changes in an application and improve its scalability and maintainability.
Pros
- Unidirectional data flow simplifies application state management
- Promotes a clear separation of concerns between components
- Enhances predictability and debugging of complex applications
- Well-suited for large-scale applications with complex data flows
Cons
- Steeper learning curve compared to traditional MVC architectures
- Can introduce boilerplate code for simple applications
- May be overkill for small or straightforward projects
- Requires careful design to avoid unnecessary complexity
Code Examples
- Creating a Dispatcher:
import { Dispatcher } from 'flux';
const AppDispatcher = new Dispatcher();
export default AppDispatcher;
- Defining an Action Creator:
import AppDispatcher from './AppDispatcher';
const TodoActions = {
addTodo: (text) => {
AppDispatcher.dispatch({
actionType: 'ADD_TODO',
text: text
});
}
};
export default TodoActions;
- Creating a Store:
import { EventEmitter } from 'events';
import AppDispatcher from './AppDispatcher';
const CHANGE_EVENT = 'change';
let _todos = [];
const TodoStore = Object.assign({}, EventEmitter.prototype, {
getAll: function() {
return _todos;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
});
AppDispatcher.register(function(action) {
switch(action.actionType) {
case 'ADD_TODO':
_todos.push(action.text);
TodoStore.emitChange();
break;
default:
// no op
}
});
export default TodoStore;
Getting Started
To start using Flux in your project:
- Install Flux:
npm install flux
- Create a dispatcher:
import { Dispatcher } from 'flux';
export default new Dispatcher();
-
Define actions and stores as shown in the code examples above.
-
In your React components, listen for store changes and trigger actions:
import React from 'react';
import TodoStore from './TodoStore';
import TodoActions from './TodoActions';
class TodoApp extends React.Component {
// Component implementation
}
export default TodoApp;
Remember to wire up your stores, actions, and components according to the Flux architecture principles.
Competitor Comparisons
The library for web and native user interfaces.
Pros of React
- More comprehensive library for building user interfaces
- Active development and large community support
- Extensive ecosystem of tools and libraries
Cons of React
- Steeper learning curve for beginners
- Requires additional tools for state management in complex applications
- Larger bundle size compared to minimal Flux implementation
Code Comparison
React component example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Flux store example:
var TodoStore = assign({}, EventEmitter.prototype, {
getAll: function() {
return _todos;
}
});
React focuses on component-based UI development, while Flux provides a unidirectional data flow architecture. React has evolved into a more comprehensive solution for building user interfaces, whereas Flux remains a simple pattern for managing application state.
React's ecosystem has grown significantly, offering a wide range of tools and libraries. Flux, being archived, lacks ongoing development and community support. However, Flux's simplicity can be advantageous for smaller projects or when a minimal state management solution is preferred.
React's component-based approach allows for more modular and reusable code, while Flux's store-centric model emphasizes centralized state management. Both have influenced modern web development practices, with React becoming a dominant force in the frontend landscape.
A JS library for predictable global state management
Pros of Redux
- Simpler and more predictable state management with a single store
- Extensive middleware ecosystem for enhanced functionality
- Better documentation and community support
Cons of Redux
- Steeper learning curve due to functional programming concepts
- More boilerplate code required for setup and actions
Code Comparison
Flux:
var TodoStore = assign({}, EventEmitter.prototype, {
getAll: function() {
return _todos;
}
});
AppDispatcher.register(function(action) {
switch(action.actionType) {
case TodoConstants.TODO_CREATE:
// Handle action
break;
}
});
Redux:
const todoReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
};
const store = createStore(todoReducer);
Redux uses a single store and reducer functions to manage state, while Flux relies on multiple stores and a central dispatcher. Redux's approach leads to more predictable state management and easier debugging. However, Redux requires more setup and understanding of functional programming concepts, which can be challenging for beginners. Flux's multiple store approach can be more intuitive for complex applications but may lead to inconsistencies in state management.
🗃️ Centralized State Management for Vue.js.
Pros of Vuex
- Tightly integrated with Vue.js, providing a seamless development experience
- Simpler API and less boilerplate code compared to Flux
- Built-in devtools for easier debugging and state management
Cons of Vuex
- Limited to Vue.js ecosystem, not as flexible for use with other frameworks
- May be overkill for small applications with simple state management needs
Code Comparison
Flux:
var TodoStore = assign({}, EventEmitter.prototype, {
getAll: function() {
return _todos;
}
});
AppDispatcher.register(function(action) {
switch(action.actionType) {
case TodoConstants.TODO_CREATE:
// Handle action
break;
}
});
Vuex:
const store = new Vuex.Store({
state: {
todos: []
},
mutations: {
addTodo(state, todo) {
state.todos.push(todo)
}
}
})
Key Differences
- Vuex uses a centralized store, while Flux allows multiple stores
- Vuex mutations are synchronous, whereas Flux actions can be asynchronous
- Vuex has a more opinionated structure, making it easier to get started but potentially less flexible for complex scenarios
Simple, scalable state management.
Pros of MobX
- Simpler and more intuitive API, reducing boilerplate code
- Automatic tracking of state changes and re-rendering
- Better performance for complex state management scenarios
Cons of MobX
- Less explicit data flow, which can make debugging more challenging
- Steeper learning curve for developers familiar with Flux architecture
- Potential for overuse of observables, leading to unnecessary re-renders
Code Comparison
MobX:
import { makeObservable, observable, action } from "mobx";
class TodoStore {
todos = [];
constructor() {
makeObservable(this, {
todos: observable,
addTodo: action
});
}
addTodo(text) {
this.todos.push({ text, completed: false });
}
}
Flux:
const TodoActions = {
addTodo(text) {
AppDispatcher.dispatch({
actionType: TodoConstants.TODO_CREATE,
text: text
});
}
};
const TodoStore = assign({}, EventEmitter.prototype, {
todos: [],
addTodo(text) {
this.todos.push({ text, completed: false });
this.emit(CHANGE_EVENT);
}
});
Summary
MobX offers a more straightforward approach to state management with automatic tracking and updates, while Flux provides a more structured and explicit data flow. The choice between the two depends on project requirements, team preferences, and the complexity of the application's state management needs.
Reactive State for Angular
Pros of ngrx/platform
- Specifically designed for Angular applications, providing tight integration
- Offers a more comprehensive state management solution with additional features like effects and entity management
- Active development and community support
Cons of ngrx/platform
- Steeper learning curve due to its complexity and RxJS integration
- Can be overkill for smaller applications
- Requires more boilerplate code compared to simpler state management solutions
Code Comparison
Flux:
var TodoStore = assign({}, EventEmitter.prototype, {
getAll: function() {
return _todos;
}
});
AppDispatcher.register(function(action) {
switch(action.actionType) {
case TodoConstants.TODO_CREATE:
// Handle action
break;
}
});
ngrx/platform:
export interface State {
todos: Todo[];
}
export const reducer = createReducer(
initialState,
on(addTodo, (state, { todo }) => ({ ...state, todos: [...state.todos, todo] }))
);
@Injectable()
export class TodoEffects {
loadTodos$ = createEffect(() => this.actions$.pipe(
ofType('[Todos] Load Todos'),
mergeMap(() => this.todosService.getTodos())
));
}
A reactive programming library for JavaScript
Pros of RxJS
- More powerful and flexible for handling complex asynchronous operations
- Provides a rich set of operators for data transformation and composition
- Supports multiple programming paradigms (functional, reactive, imperative)
Cons of RxJS
- Steeper learning curve due to its extensive API and concepts
- Can be overkill for simpler applications with basic state management needs
- Potential for performance overhead in certain scenarios
Code Comparison
Flux:
var TodoStore = assign({}, EventEmitter.prototype, {
getAll: function() {
return _todos;
}
});
AppDispatcher.register(function(action) {
switch(action.actionType) {
case TodoConstants.TODO_CREATE:
// Handle action
break;
}
});
RxJS:
const todos$ = new BehaviorSubject([]);
const addTodo$ = new Subject();
addTodo$.pipe(
map(todo => [...todos$.value, todo])
).subscribe(todos$);
todos$.subscribe(todos => {
// Update UI
});
The Flux example shows a traditional store with a dispatcher, while the RxJS example demonstrates a reactive approach using observables and subjects for managing state and actions. RxJS offers more flexibility in handling complex data flows, but Flux provides a simpler, more structured pattern for basic state management in React applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
â ï¸ The Flux project has been archived and no further changes will be made. We recommend using more sophisticated alternatives like Redux, MobX, Recoil, Zustand, or Jotai.
Flux
An application architecture for React utilizing a unidirectional data flow.
Getting Started
Start by looking through the guides and examples on Github. For more resources and API docs check out facebook.github.io/flux.
How Flux works
For more information on how Flux works check out the Flux Concepts guide, or the In Depth Overview.
Requirements
Flux is more of a pattern than a framework, and does not have any hard dependencies. However, we often use EventEmitter as a basis for Stores
and React for our Views
. The one piece of Flux not readily available elsewhere is the Dispatcher
. This module, along with some other utilities, is available here to complete your Flux toolbox.
Installing Flux
Flux is available as a npm module, so you can add it to your package.json file or run npm install flux
. The dispatcher will be available as Flux.Dispatcher
and can be required like this:
const Dispatcher = require('flux').Dispatcher;
Take a look at the dispatcher API and some examples.
Flux Utils
We have also provided some basic utility classes to help get you started with Flux. These base classes are a solid foundation for a simple Flux application, but they are not a feature-complete framework that will handle all use cases. There are many other great Flux frameworks out there if these utilities do not fulfill your needs.
import {ReduceStore} from 'flux/utils';
class CounterStore extends ReduceStore<number> {
getInitialState(): number {
return 0;
}
reduce(state: number, action: Object): number {
switch (action.type) {
case 'increment':
return state + 1;
case 'square':
return state * state;
default:
return state;
}
}
}
Check out the examples and documentation for more information.
Building Flux from a Cloned Repo
Clone the repo and navigate into the resulting flux
directory. Then run npm install
.
This will run Gulp-based build tasks automatically and produce the file Flux.js, which you can then require as a module.
You could then require the Dispatcher like so:
const Dispatcher = require('path/to/this/directory/Flux').Dispatcher;
The build process also produces de-sugared versions of the Dispatcher
and invariant
modules in a lib
directory, and you can require those modules directly, copying them into whatever directory is most convenient for you. The flux-todomvc
and flux-chat
example applications both do this.
License
Flux is BSD-licensed. We also provide an additional patent grant.
Top Related Projects
The library for web and native user interfaces.
A JS library for predictable global state management
🗃️ Centralized State Management for Vue.js.
Simple, scalable state management.
Reactive State for Angular
A reactive programming library for JavaScript
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot