Convert Figma logo to code with AI

reflux logorefluxjs

A simple library for uni-directional dataflow application architecture with React extensions inspired by Flux

5,357
329
5,357
29

Top Related Projects

17,488

Application Architecture for Building User Interfaces

60,936

A JS library for predictable global state management

27,618

Simple, scalable state management.

28,431

🗃️ Centralized State Management for Vue.js.

Reactive State for Angular

30,713

A reactive programming library for JavaScript

Quick Overview

RefluxJS is a simple library for unidirectional dataflow architecture inspired by ReactJS Flux. It provides a way to structure client-side web applications that is easy to reason about and makes state management more predictable. RefluxJS is designed to be used with React, but can be used with any other view library.

Pros

  • Simple and lightweight implementation of the Flux pattern
  • Easy to understand and implement in existing projects
  • Works well with React but is not limited to it
  • Encourages modular and maintainable code structure

Cons

  • Less feature-rich compared to more modern state management libraries like Redux
  • May not scale as well for very large and complex applications
  • Limited ecosystem and community support compared to more popular alternatives
  • Lacks built-in middleware support for handling side effects

Code Examples

  1. Creating an action:
const Actions = Reflux.createActions([
  'incrementCounter',
  'decrementCounter'
]);
  1. Creating a store:
const CounterStore = Reflux.createStore({
  listenables: Actions,

  init() {
    this.count = 0;
  },

  onIncrementCounter() {
    this.count++;
    this.trigger(this.count);
  },

  onDecrementCounter() {
    this.count--;
    this.trigger(this.count);
  }
});
  1. Using the store in a React component:
const Counter = Reflux.Component.extend({
  stores: [CounterStore],

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={Actions.incrementCounter}>Increment</button>
        <button onClick={Actions.decrementCounter}>Decrement</button>
      </div>
    );
  }
});

Getting Started

To get started with RefluxJS, follow these steps:

  1. Install RefluxJS:

    npm install reflux
    
  2. Import Reflux in your project:

    import Reflux from 'reflux';
    
  3. Create actions and stores as shown in the code examples above.

  4. Use the stores in your React components by extending Reflux.Component or using the Reflux.connect higher-order component.

  5. Dispatch actions using the created action functions to update the store and trigger changes in your components.

Competitor Comparisons

17,488

Application Architecture for Building User Interfaces

Pros of Flux

  • Official implementation by Facebook, ensuring alignment with the original Flux architecture
  • Comprehensive documentation and examples provided
  • Strong community support and integration with React ecosystem

Cons of Flux

  • More complex setup and boilerplate code required
  • Steeper learning curve for beginners
  • Less flexibility in implementation compared to Reflux

Code Comparison

Flux:

var AppDispatcher = require('./AppDispatcher');
var TodoConstants = require('./TodoConstants');

var TodoActions = {
  create: function(text) {
    AppDispatcher.dispatch({
      actionType: TodoConstants.TODO_CREATE,
      text: text
    });
  }
};

Reflux:

var TodoActions = Reflux.createActions([
  "create",
  "edit",
  "remove"
]);

TodoActions.create.listen(function(text) {
  // Handle create action
});

Key Differences

  • Flux uses a centralized dispatcher, while Reflux eliminates this concept
  • Reflux simplifies the overall architecture, reducing boilerplate code
  • Flux maintains a strict unidirectional data flow, whereas Reflux allows for more flexible patterns
  • Reflux provides a more streamlined API for creating actions and stores

Conclusion

While Flux offers a more structured and officially supported implementation, Reflux provides a simpler and more flexible alternative. The choice between the two depends on project requirements, team familiarity, and desired level of architectural strictness.

60,936

A JS library for predictable global state management

Pros of Redux

  • More structured and predictable state management with a single store
  • Powerful middleware ecosystem for handling side effects
  • Better suited for large, complex applications

Cons of Redux

  • Steeper learning curve and more boilerplate code
  • Can be overkill for simple applications
  • Requires careful consideration of immutability

Code Comparison

Redux:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

Reflux:

const CounterStore = Reflux.createStore({
  init() {
    this.count = 0;
    this.listenTo(Actions.increment, this.onIncrement);
  },
  onIncrement() {
    this.count++;
    this.trigger({ count: this.count });
  }
});

Redux uses a reducer function to handle state changes, while Reflux uses a store object with methods. Redux requires explicit action creators and a switch statement in the reducer, whereas Reflux uses a more event-driven approach with listeners. Redux's approach is more verbose but offers better predictability and easier testing, while Reflux's syntax is more concise but may be less scalable for complex applications.

27,618

Simple, scalable state management.

Pros of MobX

  • More intuitive and less boilerplate code required
  • Automatic tracking of observable state changes
  • Better performance for complex state management scenarios

Cons of MobX

  • Steeper learning curve for developers new to reactive programming
  • Less explicit data flow, which can make debugging more challenging
  • Potential for overuse of observables, leading to unnecessary re-renders

Code Comparison

RefluxJS:

var Actions = Reflux.createActions(["increment", "decrement"]);
var Store = Reflux.createStore({
    listenables: Actions,
    onIncrement: function() { this.trigger(this.count++); },
    onDecrement: function() { this.trigger(this.count--); }
});

MobX:

class Store {
    @observable count = 0;
    @action increment = () => { this.count++; }
    @action decrement = () => { this.count--; }
}

MobX uses decorators and class syntax for a more concise implementation, while RefluxJS relies on a more explicit action-store relationship. MobX's reactive approach automatically tracks and updates state changes, whereas RefluxJS requires manual triggering of updates. The MobX example demonstrates its simpler syntax and reduced boilerplate compared to RefluxJS.

28,431

🗃️ Centralized State Management for Vue.js.

Pros of Vuex

  • Tightly integrated with Vue.js ecosystem, providing seamless state management
  • Offers a more structured and opinionated approach to state management
  • Includes built-in devtools for easier debugging and time-travel debugging

Cons of Vuex

  • Steeper learning curve for developers new to Vue.js or state management concepts
  • Can be overkill for smaller applications with simple state requirements
  • Requires more boilerplate code compared to Reflux

Code Comparison

Vuex:

const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++ }
  }
})

Reflux:

const CounterStore = Reflux.createStore({
  listenables: [Actions],
  onIncrement() {
    this.count++;
    this.trigger(this.count);
  }
});

Both Vuex and Reflux are state management libraries, but they differ in their approach and integration. Vuex is specifically designed for Vue.js applications, offering a more structured and centralized state management solution. Reflux, on the other hand, is a more flexible library that can be used with various frameworks, including React.

Vuex provides a single store with clearly defined mutations and actions, making it easier to track state changes and debug applications. Reflux uses a more decentralized approach with multiple stores and actions, which can be beneficial for larger applications with complex state management needs.

While Vuex requires more initial setup and boilerplate code, it offers better integration with Vue.js and its ecosystem. Reflux, being more flexible, can be easier to adopt in existing projects or when working with multiple frameworks.

Reactive State for Angular

Pros of ngrx/platform

  • Comprehensive state management solution specifically designed for Angular applications
  • Implements Redux pattern with RxJS, providing powerful tools for handling asynchronous operations
  • Extensive ecosystem with additional libraries for effects, entity management, and dev tools

Cons of ngrx/platform

  • Steeper learning curve due to its complexity and reliance on RxJS concepts
  • Can introduce boilerplate code, especially for smaller applications
  • Tightly coupled with Angular, limiting its use in other frameworks or vanilla JavaScript projects

Code Comparison

ngrx/platform:

@Effect()
loadBooks$ = this.actions$.pipe(
  ofType(BookActionTypes.Load),
  mergeMap(() => this.bookService.getAll()
    .pipe(
      map(books => new LoadBooksSuccess(books)),
      catchError(error => of(new LoadBooksFailure(error)))
    ))
);

refluxjs:

var actions = Reflux.createActions([
  "loadBooks",
  "loadBooksSuccess",
  "loadBooksFailure"
]);

actions.loadBooks.listen(function() {
  bookService.getAll().then(actions.loadBooksSuccess, actions.loadBooksFailure);
});

Summary

ngrx/platform offers a robust state management solution for Angular applications, leveraging RxJS and providing a comprehensive ecosystem. However, it comes with a steeper learning curve and more boilerplate compared to refluxjs. refluxjs, on the other hand, is simpler and more flexible but lacks the advanced features and Angular-specific optimizations of ngrx/platform.

30,713

A reactive programming library for JavaScript

Pros of RxJS

  • More powerful and flexible, supporting a wide range of reactive programming patterns
  • Extensive operator library for complex data transformations
  • Cross-platform compatibility (browser, Node.js, and other JavaScript runtimes)

Cons of RxJS

  • Steeper learning curve due to its comprehensive API and concepts
  • Can be overkill for simpler applications with basic state management needs
  • Larger bundle size compared to Reflux

Code Comparison

RxJS:

import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';

of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 === 0),
    map(n => n * 2)
  )
  .subscribe(console.log);

Reflux:

var Actions = Reflux.createActions(['increment', 'decrement']);
var store = Reflux.createStore({
  listenables: Actions,
  onIncrement: function() { this.trigger(this.count++); },
  onDecrement: function() { this.trigger(this.count--); }
});

RxJS offers a more functional approach with powerful operators, while Reflux provides a simpler, action-based state management system. RxJS is better suited for complex, reactive applications, whereas Reflux is more straightforward for basic state management in React applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

RefluxJS

A simple library for unidirectional dataflow architecture inspired by ReactJS Flux.

NPM Version Bower Version Build Status NPM Downloads

Sauce Test Status


Installation

You can currently install the package as a npm package, a bower component, or import it from a CDN.

NPM

The following command installs RefluxJS as a npm package:

npm install reflux

Then, in your script, you can gain a reference to RefluxJS like so: var Reflux = require('reflux');

Bower

The following command installs reflux as a bower component that can be used in the browser:

bower install reflux

Then the files may be imported into your html file via bower_components/reflux/dist/reflux.js or bower_components/reflux/dist/reflux.min.js. At that point a Reflux variable will be globally available to you. It is suggested that you import RefluxJS after React.

CDN

RefluxJS is available at jsdelivr.

You may import the CDN files directly through a script tag. At that point a Reflux variable will be globally available to you. It is suggested that you import RefluxJS after React.


Overview

The main function of Reflux is to introduce a more functional programming style architecture by eschewing MVC like pattern and adopting a single data flow pattern.

+---------+       +--------+       +-----------------+
¦ Actions ¦------>¦ Stores ¦------>¦ View Components ¦
+---------+       +--------+       +-----------------+
     ^                                      ¦
     +--------------------------------------+

The pattern is composed of actions and data stores, where actions initiate new data to pass through data stores before coming back to the view components again. If a view component has an event that needs to make a change in the application's data stores, they need to do so by signaling to the stores through the actions available.


Usage

For usage, you need to create actions which can be called from React components. Those actions are listened to by stores which hold and update data. In turn those stores are hooked up to React components and set state within them as it is updated within the store.

Therefore the 3 main concepts to know are:

  1. creating actions
  2. creating stores
  3. hooking stores to React components

Creating Actions

Create an action by calling Reflux.createAction with an optional options object.

var statusUpdate = Reflux.createAction();

An action is a function object that can be invoked like any other function.

statusUpdate(data); // Invokes the action statusUpdate

There is also a convenience function for creating multiple actions.

var Actions = Reflux.createActions([
    "statusUpdate",
    "statusEdited",
    "statusAdded"
]);

// Actions object now contains the actions
// with the names given in the array above
// that may be invoked as usual

Actions.statusUpdate();

More on Actions:

Actions can also:

  • load files asynchronously with child actions
  • do preEmit and shouldEmit checking
  • have many shortcuts for easy usage

See Reflux Action Documentation for more.


Creating Stores

Create a data store much like ReactJS's own React.Component by creating a class extending Reflux.Store. The store has a state property much like a component, and uses setState like a component as well. You may set up all action listeners in the constructor and register them by calling the store's own listenTo function.

class StatusStore extends Reflux.Store
{
    constructor()
    {
        super();
        this.state = {flag:'OFFLINE'}; // <- set store's default state much like in React
        this.listenTo(statusUpdate, this.onStatusUpdate); // listen to the statusUpdate action
    }

    onStatusUpdate(status)
    {
        var newFlag = status ? 'ONLINE' : 'OFFLINE';
        this.setState({flag:newFlag});
    }
}

In the above example, whenever the action statusUpdate is called, the store's onStatusUpdate callback will be called with whatever parameters were sent in the action. E.g. if the action is called as statusUpdate(true) then the status argument in the onStatusUpdate function is true.

Stores also integrate easily with sets of actions via things like this.listenables. When an actions object (or an Array of multiple actions objects) is applied to this.listenables you may automatically add listeners simply by naming convention. Just name the functions either after the action name (such as actionName, or the camelcased action name preceded with "on", (such as onActionName).

var Actions = Reflux.createActions(['firstAction', 'secondAction']);

class StatusStore extends Reflux.Store
{
    constructor()
    {
        super();
        this.listenables = Actions;
    }

    onFirstAction()
    {
        // calls on Actions.firstAction();
    }

	onSecondAction()
	{
		// calls on Actions.secondAction();
	}
}

More on Stores:

Reflux stores are very powerful. They can even do things like contribute to a global state that can be read and set for partial or full-state time-travel, debugging, etc.

See Reflux Store Documentation to learn more about stores.


Hooking Stores to Components

Once you've created actions and stores, now the last step in working RefluxJS is to hook those stores to a React component.

This is done as simply as extending Reflux.Component instead of React.Component and setting the store(s) to use. Reflux.Component itself extends React.Component, so you use them the exact same way. The only difference is that Reflux.Component allows you to set stores for the component to get state from:

class MyComponent extends Reflux.Component
{
    constructor(props)
    {
        super(props);
        this.state = {}; // our store will add its own state to the component's
        this.store = StatusStore; // <- just assign the store class itself
    }

    render()
    {
        var flag = this.state.flag; // <- flag is mixed in from the StatusStore
        return <div>User is {flag}</div>
    }
}

When the component mounts it will either create a singleton instance of StatusStore (if one isn't already made) or use an already made singleton (if it was already created by another component that uses the store).

Of important note is that you can:

  1. Set multiple stores by setting this.stores (the plural) and setting it to an Array of store classes.
  2. Set a this.storeKeys Array to restrict only certain parts of the store being mixed into the component state.

There is also a mapStoreToState method in the documentation for those that want absolute control over how a store's state is mapped to a component.

class MyComponent extends Reflux.Component
{
    constructor(props)
    {
        super(props);
        this.state = {type:'admin'}; // <- note that we can still use normal state
        this.stores = [StatusStore, AnotherStore];
        this.storeKeys = ['flag', 'info'];
    }

    render()
    {
        var flag = this.state.flag;
        var info = this.state.info;
        var type = this.state.type;
        return <div>User is {flag}, info: {info}, type: {type}</div>
    }
}

The above will mix in properties from the state of both StatusStore and AnotherStore. However, because of this.storeKeys it will only mix in the properties flag and info from them. So any other properties within those stores will not get mixed in. So even if a store contained a type property in its state it would not get mixed in, and the type value we set as a normal part of the component state is safe.

More on using Reflux style components:

Reflux's simple and intuitive way of integrating stores into components is easy and powerful. You can aggregate stores together on a component-by-component basis, filter which parts of the stores come through and which don't, or even do a detailed manual mapping of exactly how you want the state from stores to map to the state in a particular component.

See Reflux Style Component Documentation to learn more.


Documentation

What you've just read is a "view from 10,000 feet" type overview of getting started with RefluxJS. For serious learning see the documentation.

NPM DownloadsLast 30 Days