Friday, November 1, 2024
Google search engine
HomeLanguagesWhat are the differences between Redux and Flux in ReactJS ?

What are the differences between Redux and Flux in ReactJS ?

During the phase of applications or software development, we gather the requirements of customers to create a solution to solve the problem of customers or businesses. To solve problems we rely on different technologies and architecture patterns. for a long time, developers were using MVC (Model-View-Controller) pattern. As we know that after every month new technologies come into the market with new features which replace previous ones. So the same way development team of Facebook come up with important changes and release flux which becomes an alternative option for MVC architecture. and after flux, there has been another framework Redux comes into the market. Let’s discuss Redux vs Flux in this article.

Flux: Flux is the application architecture or we can say JavaScript architecture that uses for building client-side web applications or UI for client applications. you can start using flux without a lot of new code. flux overcome the drawbacks of MVC such as instability and complexity.

Example: In this example, we create a TODO list application. This example contains functionality that you can add a task in the TODO list along with you can remove the list of tasks.

Step 1:  Create a new react app using the below commands.

devendra@root:~/Desktop$ npx create-react-app todoapp
devendra@root:~/Desktop/todoapp$ npm install redux react-redux –save  

Step 2: Create a folder structure in your code editor as given below in the screenshot you can create files manually or using commands as well.

Project Structure:

todo app folder structure

Step 3 (Actions): Actions are things that happen during the lifetime of your application. In our application when the user clicks on create button a function CRAETE_TODO will call and a new task will be added to the list. The same DELETE_TODO  function will perform a delete action when the Delete button is clicked. This is an example of the Action component.

TodoActions.js

Javascript




import dispatcher from "../dispatcher";
 
/* Create task function */
export function createTodo(text) {
    dispatcher.dispatch({
        type: "CREATE_TODO",
        text,
    });
}
 
/* Delete task function */
export function deleteTodo(id) {
    dispatcher.dispatch({
        type: "DELETE_TODO",
        id,
    });
}


Step 4: Dispatchers

Think of the Dispatcher as a router. Actions are sent to the Dispatcher who calls the appropriate callbacks.

dispatcher.js

Javascript




import { Dispatcher } from "flux";
 
export default new Dispatcher;


Step 5 (Store):

A store is a place that holds the app’s state. It is very easy to create a store once you have reducers. We are passing store property to the provider element, which wraps our route component.

Javascript




import { EventEmitter } from 'events';
 
import dispatcher from '../dispatcher';
 
class TodoStore extends EventEmitter {
    constructor() {
        super();
 
        this.todos = [
            {
                id: 16561,
                text: 'hello'
            },
            {
                id: 16562,
                text: 'another todo'
            },
        ];
    }
 
    createTodo(text) {
        const id = Date.now();
 
        this.todos.push({
            id,
            text
        });
 
        this.emit('change');
    }
 
    deleteTodo(id) {
        this.todos = this.todos.filter((elm) => {
            return (elm.id != id);
        });
        this.emit('change');
    }
 
    getAll() {
        return this.todos;
    }
 
    handleActions(action) {
        switch (action.type) {
            case 'CREATE_TODO': {
                this.createTodo(action.text);
                break;
            }
            case 'DELETE_TODO': {
                this.deleteTodo(action.id);
                break;
            }
        }
    }
}
 
const todoStore = new TodoStore();
dispatcher.register(todoStore.handleActions.bind(todoStore));
export default todoStore;


Step 6 (Root Component): The index.js component is the root component of the app. Only the root component should be aware of a redux. The important part to notice is the connect function which is used for connecting our root component App to the store. This function takes a select function as an argument. The select function takes the state from the store and returns the props (visibleTodos) that we can use in our components.

Todolist.js

Javascript




import React from 'react';
import Todo from '../components/Todo';
import TodoStore from '../stores/TodoStore.js';
import * as TodoActions from '../actions/TodoActions';
 
export default class Todolist extends React.Component {
    constructor() {
        super();
 
        this.state = {
            todos: TodoStore.getAll(),
        };
        this.inputContent = '';
    }
 
    // We start listening to the store changes
    componentWillMount() {
        TodoStore.on("change", () => {
            this.setState({
                todos: TodoStore.getAll(),
            });
        });
    }
 
    render() {
 
        const TodoComp = this.state.todos.map(todo => {
            return <Todo key={todo.id} {...todo} />;
        });
 
        return (
            <div>
                <h1> GFG Todo list</h1>
                <input type="text" onChange=
                    {(evt) => this.inputContent = evt.target.value} />
                <button onClick={() => TodoActions
                    .createTodo(this.inputContent)}>Create!</button>
                <ul>{TodoComp}</ul>
            </div>
        );
    }
}


Step 7: Now we will delete the task component.

Todo.js

Javascript




import React from "react";
import * as TodoActions from '../actions/TodoActions';
 
export default class Todo extends React.Component {
 
    render() {
        return (
            <li>
                <span>{this.props.text}</span>
                <button onClick={() => TodoActions
                    .deleteTodo(this.props.id)}>delete</button>
            </li>
 
        );
    }
}


Step 8: Other components 

index.js

Javascript




import React from 'react';
import { render } from 'react-dom';
import Todolist from './pages/Todolist';
 
const app = document.getElementById('root');
 
// render(React.createElement(Layout), app);
render(<Todolist />, app);


Step to run application: Open the terminal and type the following command.

npm start

Output:Create button will add a task to Todo list, similarly Delete button removes the task from the Todo list

Redux: Redux is a predictable state container for JavaScript apps. Dan Abramov & Andrew Clark developed Redux in 2015. Redux itself library that can be used with any UI layer or framework, including React, Angular, Ember, and vanilla JS. Redux can be used with React. both are independent of each other. Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.

Example: Now we will see a simple example counter using react-redux. In this example we store a state of button clicks and used that states for further buttons to click for example we create four buttons increment (+), decrement (-),  increment if odd, increment async. 

  • increment (+), decrement (-): these two buttons will increment click by +1 and -1
  • increment if odd: this button will only increment click if previous two buttons (+)and (-) click is odd i.e. if the click is 7 then only this button will increment by +1 and now clicks will be 8 otherwise this will not increment if previous buttons (+) and (-) clicks were 6 because 6 is even and increment if odd button only clicks when the previous state is odd click.
  • increment async: This button will increment click after halt or wait of 1000 mili. sec.

Below is the step by step implementation:

Step 1: Create a new react app using the below commands.

npx create-react-app counterproject
npm install redux react-redux --save

Step 2: Create all required Files and Folders.

Project Structure: It will look like the following.

files and folders

Step 3: Counter.js is a Presentational Component, which is concerned with how things look such as markup, styles. It receives data and invokes callbacks exclusively via props. It does not know where the data comes from or how to change it. It only renders what is given to them. This is the root component for the counter to render everything in UI.

Counter.js

Javascript




import React, { Component } from 'react'
import PropTypes from 'prop-types'
 
class Counter extends Component {
    constructor(props) {
        super(props);
        this.incrementAsync = this.incrementAsync.bind(this);
        this.incrementIfOdd = this.incrementIfOdd.bind(this);
    }
 
    incrementIfOdd() {
        if (this.props.value % 2 !== 0) {
            this.props.onIncrement()
        }
    }
 
    incrementAsync() {
        setTimeout(this.props.onIncrement, 1000)
    }
 
    render() {
        const { value, onIncrement, onDecrement } = this.props
        return (
 
            <p>
                <h1>GeeksForGeeks Counter Example</h1>
                Clicked: {value} times
                {' '}
                <button onClick={onIncrement}>
                    +
                </button>
                {' '}
                <button onClick={onDecrement}>
                    -
                </button>
                {' '}
                <button onClick={this.incrementIfOdd}>
                    Increment if odd
                </button>
                {' '}
                <button onClick={this.incrementAsync}>
                    Increment async
                </button>
            </p>
        )
    }
}
 
Counter.propTypes = {
    value: PropTypes.number.isRequired,
    onIncrement: PropTypes.func.isRequired,
    onDecrement: PropTypes.func.isRequired
}
 
export default Counter


Step 4: Counter.spec.js contains what to change when particular buttons of components are clicked.

Javascript




import React from 'react'
import { shallow } from 'enzyme'
import Counter from './Counter'
 
function setup(value = 0) {
    const actions = {
        onIncrement: jest.fn(),
        onDecrement: jest.fn()
    }
    const component = shallow(
        <Counter value={value} {...actions} />
    )
 
    return {
        component: component,
        actions: actions,
        buttons: component.find('button'),
        p: component.find('p')
    }
}
 
describe('Counter component', () => {
    it('should display count', () => {
        const { p } = setup()
        expect(p.text()).toMatch(/^Clicked: 0 times/)
    })
 
    it('first button should call onIncrement', () => {
        const { buttons, actions } = setup()
        buttons.at(0).simulate('click')
        expect(actions.onIncrement).toBeCalled()
    })
 
    it('second button should call onDecrement', () => {
        const { buttons, actions } = setup()
        buttons.at(1).simulate('click')
        expect(actions.onDecrement).toBeCalled()
    })
 
    it('third button should not call onIncrement if the counter is even', () => {
        const { buttons, actions } = setup(42)
        buttons.at(2).simulate('click')
        expect(actions.onIncrement).not.toBeCalled()
    })
 
    it('third button should call onIncrement if the counter is odd', () => {
        const { buttons, actions } = setup(43)
        buttons.at(2).simulate('click')
        expect(actions.onIncrement).toBeCalled()
    })
 
    it('third button should call onIncrement if the counter is
    odd and negative', () => {
    const { buttons, actions } = setup(-43)
    buttons.at(2).simulate('click')
    expect(actions.onIncrement).toBeCalled()
})
 
it('fourth button should call onIncrement in a second', (done) => {
    const { buttons, actions } = setup()
    buttons.at(3).simulate('click')
    setTimeout(() => {
        expect(actions.onIncrement).toBeCalled()
        done()
    }, 1000)
})
})


Step 4: Reducers 

This is a reducer, a function that takes a current state value and an action object describing “what happened”, and returns a new state value. A reducer’s function signature is: (state, action) => newState. it means a reducer function takes two parameters state and action. The Redux state should contain only plain JS objects, arrays, and primitives. The root state value is usually an object. It’s important that you should not mutate the state object, but return a new object if the state changes. You can use any conditional logic you want in a reducer. In this example, we use a switch statement, but it’s not required.

index.js

Javascript




export default (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1
        case 'DECREMENT':
            return state - 1
        default:
            return state
    }
}


Index.spec.js

Javascript




import counter from './index'
 
describe('reducers', () => {
    describe('counter', () => {
        it('should provide the initial state', () => {
            expect(counter(undefined, {})).toBe(0)
        })
 
        it('should handle INCREMENT action', () => {
            expect(counter(1, { type: 'INCREMENT' })).toBe(2)
        })
 
        it('should handle DECREMENT action', () => {
            expect(counter(1, { type: 'DECREMENT' })).toBe(0)
        })
 
        it('should ignore unknown actions', () => {
            expect(counter(1, { type: 'unknown' })).toBe(1)
        })
    })
})


Step 5:  Store

All container components need access to the Redux Store to subscribe to it. For this, we need to pass it(store) as a prop to every container component. However, it gets tedious. So we recommend using a special React Redux component called which makes the store available to all container components without passing it explicitly. It is used once when you render the root component.

index.js

Javascript




import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import Counter from './components/Counter'
import counter from './reducers'
 
const store = createStore(counter)
const rootEl = document.getElementById('root')
 
const render = () => ReactDOM.render(
    <Counter
        value={store.getState()}
        onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
        onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
    />,
    rootEl
)
 
render()
store.subscribe(render)


Step to run the application: Open the terminal and type the following command.

npm start

Output:

Difference between Redux and Flux: 

Sr.no

Redux

Flux

1. It was developed by Dan Abramov & Andrew Clark. It was developed by Facebook.
2.  It is an Open-source JavaScript library used for creating the UI. It is Application architecture designed to build client-side web apps.
3.

Redux has mainly two components  

  • Action Creator
  • Store

Flux has main four components :

  • Action
  • Dispatcher
  • Store
  • View
4. Redux does not have any dispatcher. Flux has a single dispatcher.
5.  Redux has only a single store in the application. Flux has multiple stores in one application.
6.  In Redux, Data logics are in the reducers.  In flux, Data logic is in store.
7.  In Redux store’s state cannot be mutable In flux store’s state can be mutable.
8.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments