React is a popular JavaScript library for building a user interfaces which offers multiple state management solutions. Two prominent choices are Redux and Facebook Flux. Both aim to simplify the state management in the React app but they have different approaches and syntax and a unidirectional data flow, making applications more predictable and easier to debug.
ReduxRedux is a predictable state container for JavaScript applications, often used with libraries like React for building user interfaces. It helps manage the state of an application by providing a central store, making it easier to understand, debug, and test.
- Actions: Plain JavaScript objects describing the type of state change and optionally carrying payload data. (e.g., {type: ‘INCREMENT_COUNTER’, payload: 1 })
- Reducers: Pure functions that takes the current state and action, returning the new application state. (e.g., function counterReducer(state = 0, action) { … })
- Store: Holds the entire application state and provides methods for getting the current state dispatching actions and subscribing to state changes.
Steps to create a simple counter using React and Redux In this example, Redux is used for state management in a simple React counter application. The Counter component displays the current count and dispatches actions to increment or decrement the value stored in the Redux store.
Step 1: Install React
npx create-react-app my-app Step 2: Install Redux and React-Redux
npm install redux react-redux Set up your Redux store, reducers, actions, and components
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", "react-redux": "^4.0.4", "redux": "^5.0.1", "web-vitals": "^2.1.4" } Folder Structure (Redux Implementation): folder sructure Example: This example shows the building of counter app using redux.
JavaScript
// actionTypes.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
JavaScript
// counterReducer.js
import * as actionTypes from "../actions/actionTypes";
const initialState = {
count: 0,
};
const counterReducer =
(state = initialState, action) => {
switch (action.type) {
case actionTypes.INCREMENT:
return {
...state,
count: state.count + 1,
};
case actionTypes.DECREMENT:
return {
...state,
count: state.count - 1,
};
default:
return state;
}
};
export default counterReducer;
JavaScript
// store.js
import { createStore } from "redux";
import counterReducer from
"../reducers/counterReducer";
const store = createStore(counterReducer);
export default store;
JavaScript
// store.js
import { createStore } from "redux";
import counterReducer from
"../reducers/counterReducer";
const store = createStore(counterReducer);
export default store;
JavaScript
// app.js
import React from "react";
import { Provider } from "react-redux";
import Counter from "./components/Counter";
import store from "./store/store";
const App = () => {
return (
<>
<Provider store={store}>
<Counter />
</Provider>
</>
);
};
export default App;
Code Explanation:- The application starts with an initial state (count: 0) stored in the Redux store.
- The Counter component displays the current count value retrieved from the store using useSelector.
- Clicking the increment/decrement buttons triggers their respective onClick handlers.
- These handlers dispatch actions (INCREMENT or DECREMENT) to the Redux store using useDispatch.
- The counterReducer receives the dispatched action and updates the state accordingly (incrementing or decrementing the count).
- The updated state is reflected in the Redux store.
- Since the Counter component is connected to the store, it re-renders automatically with the new count value.
Output:
 FluxFlux is an architectural pattern used for building client-side web applications. It provides a unidirectional data flow that makes the application more predictable and easier to debug. Flux is not a framework or a library; rather, it’s a pattern or set of conventions for structuring your application.
- Actions: Similar to Redux actions, describing the intended state change.
- Dispatcher: A central hub that receives actions and broadcasts them to registered stores.
- Stores: JavaScript objects holding application state slices and logic for updating their own state in response to dispatched actions.
Steps to create a simple counter using React and FluxWe are using a Flux to manage the state in counter application. The Dispatcher handles actions to increment or decrement the counter, while registered listeners update the component state and re render.
Note: When you try to install flux using npm install flux, you will likely encounter warning message from npm indicating that the package is deprecated. This is a clear sign that it is time to consider alternatives. The official documentation for the flux package itself recommends using more sophisticated alternatives like Redux, MobX. When encountered such error, Try installing with npm install flux –force.
Step 1: Install React
npm create-react-app my-app Step 2: Install Flummoxnpm install flux 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" }
Folder Structure (Facebook Flux Implementation): Example: This example shows the building of counter app using Facebook flux.
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 (
<>
<h2>The Count is: {count}</h2>
<button onClick={increFn}>
Increment
</button>
<button onClick={decreFn}>
Decrement
</button>
<p style={{ color: 'green', fontSize: '34px' }}>
GeeksForGeeks
</p>
</>
);
};
export default App;
Code Explanation- This code implements a basic counter application using Flux principles.
- Actions flow through the dispatcher to update the global counter state.
- Components register as listeners to be notified of state changes and update their UI accordingly.
Output:
 Difference between Redux and Facebook Flux
Feature | Redux | Flux |
---|
Architecture | Single centralized store | Multiple decentralized stores |
---|
Data Flow | Strict unidirectional data flow | Unidirectional data flow |
---|
State Management | Managed with reducers | Managed with multiple stores |
---|
Middleware | Robust middleware support | Basic middleware support |
---|
Complexity | More complex, suitable for large applications | Simpler, suitable for smaller applications |
---|
ConclusionUse Redux for large, complex applications that require a highly structured and predictable state management system with strong debugging capabilities and middleware support, benefiting from a single source of truth and a rich ecosystem of tools. On the other hand, Flux is better suited for small to medium-sized applications, offering a simpler and more flexible architecture with multiple stores, easier learning curve, and more control over implementation details. Choose based on the application’s complexity, team familiarity, and specific state management needs.
|