Redux is an evolution of the concepts introduced by Flux. Having a general understanding of Flux will assist you in learning Redux.
By the end of this article, you should be able to:
Flux is a front-end application architecture developed by Facebook for use with React. It is not a library or framework but a design pattern for structuring applications. Flux enforces a unidirectional data flow, improving predictability and maintainability.
Actions initiate the data flow in Flux. An action is a simple JavaScript object containing a type that defines the kind of change to be performed. Actions may include additional data (payload) needed to update the state.
The dispatcher is responsible for distributing actions to the appropriate store. It acts as a central hub that ensures actions reach the relevant parts of the application.
The store maintains the application state and updates it in response to dispatched actions. It registers a callback function with the dispatcher to listen for incoming actions, modifies the state accordingly, and notifies views of any changes.
Views are responsible for rendering the user interface. They listen for state changes from the store and update the UI accordingly. Views can also dispatch actions in response to user interactions, completing the Flux loop.
Flux follows a unidirectional data flow:
Redux is a library that implements the Flux architecture with some modifications. It introduces a streamlined data flow while preserving the core concepts of Flux.
The entire state of the application is stored in a single JavaScript object called the state tree. This centralization simplifies debugging and state management.
The only way to change state is by dispatching an action. This ensures that state changes are predictable and follow a controlled process.
Reducers are pure functions that take the previous state and an action as arguments and return a new state. They do not mutate the previous state, ensuring predictability.
The Redux cycle follows these steps:
Follow these steps to create a basic Redux implementation.
mkdir redux_project
cd redux_project
npm init -y
npm install redux
Create a file store.js:
const { createStore } = require('redux');
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
const store = createStore(counterReducer);
module.exports = store;
Create a file index.js:
const store = require('./store');
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
Middleware extends Redux functionality by intercepting dispatched actions before they reach the reducer. It enables features such as asynchronous data fetching.
Redux is useful for: