Getting Started With Redux
Introduction:
Currently, there are many scripting languages which provide a component-based approach to develop a web application, like Angular, React etc. To develop such an application developer needs to create components based on the design of the application, and component can communicate with each other via properties and events. Parent component can pass data through properties and a child component can pass data to the parent via events.
With this conventional approach, there are few disadvantages like,
- We need to make extra code to manage to communicate between components which are not in a parent-child relationship
- There can be duplicate data on the client side which is used by one or more component and if data updated by one component and other component(s) may not aware of that change.
Redux Building Blocks:
Redux provides the solution for the above issues. Redux is a javascript framework which allows a developer to manage application state. Redux has 3 building blocks,
- Store
- Actions
- Reducer
Store
A store is a JSON object where all data is stored and it is just a JavaScript object which contains all property for data and all components use this data object only. So there will be no duplicate data and if one component updates a part of a data all other components, which are interested to get notified, get notified and can perform certain actions. Below is the example how to store object,
{
items:[],
users:[],
token:’Basic a546jksghduil$@aedfioj==’
}
Actions
Actions are the events like a click of a button, generally triggered by user interaction. Below are some examples of actions, which we can use in reducers using “switch case” statement.
ADD_ITEM = ‘ADD_ITEM’;
GET_ITEM = ‘GET_ITEM’;
DELETE_ITEM = ‘DELETE_ITEM’;
DELETE_ALL_ITEMS = ‘DELETE_ALL_ITEMS’;
Reducer
Reducer is a pure function which returns a state based on actions performed by user. Pure functions is a function which always returns same output for same input. For example,
function reducer(state, action) {
switch (action.type) {
case: ‘INCREMENT’:
return { count: state.count + 1 };
}
}
Above function is a pure function because it always returns the same result if we pass the same input.