Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What are the three principles that Redux follows ?

  • Last Updated : 06 Oct, 2021

Back in time when the buzz about app development had just started, frontend was easy to achieve. However, with an increasing focus on end-user experience, the complexity to develop frontend frontend is rising and becoming overwhelming.

To meet new-age users’ pressing and evolving demands, frontend developers look at Vue to help them get over the woes of complexity. In addition to this, Angular and React are possible choices. However, frontend applications lack consistency, which endured the need for a stable container for JavaScript applications. As a result, redux was developed to help frontend developers write applications for consistent behaviour. In addition to this, redux also helps tackle the React performance issues. As a result, Redux is constant when it comes to running in different environments–native, server, and client. Usually, Redux works with React to eliminate issues encountered with the state management in massive applications. Furthermore, since React is troublesome to resume components as it is tightly coupled with the root components, redux helps reduce the complexity. In addition to this, it also offers global accessibility for building easy-to-test applications.

Get to the basics first if you are just getting started with redux and want to explore it in detail.

In order to understand the core of redux, you only need to know three principles.

  1.  Redux is a Single Source of Truth: The global state of an app is stored within an object tree in a single store. As a result, it becomes easier to build universal apps due to the server’s state being serialized into the client without any extra codes. A single state tree, in turn, makes it easy to inspect an app. Besides this, it also enables a faster and shorter development cycle. Furthermore, some of the functionalities that have been traditionally tough to implement, such as Undo/Redo, can become trivial for implementation when the state is in a single tree.
  2.  The State is Read-only State: There is only one way for changing the state–emit an action or an object that describes what happened. As per the second principle, neither the network nor the views callbacks would ever write to the state. Instead of it, these express intent for the transformation of the form. Since all of these changes are centralized and these can happen only in a strict order, there are no conditions to look for. Since actions are plain objects, these can be serialized, logged, stored, and then replayed to debug or test.
  3. The Modifications are Done with Pure Functions: In order to specify how can the state tree be transformed by actions, you can write pure reducers. The reducers are merely pure functions, which take the previous state as well as action and move it to the next state. You should remember that you should return to new state objects other than mutating to the last state. For first, you should start with one reducer. Now, while your application grows, you can split it off into small reducers, which can handle specific parts of the state tree. Since reducers are merely functions, you should control the order, wherein the order can turn into reusable reducers for the common tasks.

 



Creating React Application as well as Installing Module:

Step 1: Initially, create a React app using the below-mentioned command:

npx create-react-app Principle

Step 2: Once you create the folder with the appropriate folder name–Principle–and go along with it with the following command:

cd Principle

Step 3: Once you are done creating the ReactJS application, install the modules with the below-mentioned command:

npm install

Project Structure: It will look like the following:

Example: In the below example, we begin with the data layer by storing information. As per the first principle, Redux is a singular store for data sharing. Hence, we will start with creating a singleton for storage. According to the second principle, the pure functions have a characteristic to be predictable. These functions will not have any database calls or network calls. When we will call pure functions using the same argument or parameter sets, the same value will be returned.  The following code is to be written in App.js. In addition to this, we will connect view layer to state layer with React-Redux. In the code below, the previous state will change when an action is triggered by the user, which means that upon will return to the new state.

App.js




import React from "react";
import { connect } from "react-redux";
  
const applyFilter = (searchFruite) => (article) => article
  .name.toLowerCase().includes(searchFruite.toLowerCase());
  
const App = ({ cricketerList, searchFruite, onSearch }) => (
  <div>
    <Search value={searchFruite} onSearch={onSearch}>
      <p>Search your favourite cricketer</p>
    </Search>
  
    <UL list={cricketerList.filter(applyFilter(searchFruite))} />
  </div>
);
  
const Search = ({ value, onSearch, children }) => (
  <div>
    {children}{" "}
    <input
      value={value}
      onChange={(event) => onSearch(event.target.value)}
      type="text"
    />
  </div>
);
  
const UL = ({ list }) => (
  <ul>
    {list.map((cricketer) => (
      <li key={cricketer.id}>
        <span>{cricketer.name}</span>
      </li>
    ))}
  </ul>
);
  
// Connecting view layer to state layer with react-redux
const mapStateToProps = (state) => ({
  cricketerList: state.cricketerState.cricketer,
  searchFruite: state.searchState.searchFruite,
});
  
const mapDispatchToProps = (dispatch) => ({
  onSearch: (searchFruite) =>
    dispatch({
      type: "SEARCH_SET",
      searchFruite,
    }),
});
  
export default connect(mapStateToProps, 
              mapDispatchToProps)(App);

As per the principle, the entire state of your application can be represented as a unified JavaScript object. The following data will be stored in cricketerReducer.js.

cricketerReducer.js




const INITIAL_STATE = {
  cricketer: [
    { id: "0", name: "Rahul Sharma", type: "Spin Bolwer" },
    { id: "1", name: "Rahul Tewatia", type: "All-Rounder" },
    { id: "2", name: "Virat Kohli", type: "Batsman" },
    { id: "3", name: "Suresh Raina", type: "Batsman" },
    { id: "4", name: "KL Rahul", type: "Batsman - WK" },
    { id: "5", name: "Rohit Sharma", type: "Batsman" },
    { id: "6", name: "Deepak Chahar", type: "Fast Bowler" },
    { id: "7", name: "Ms Dhoni", type: "Batsman-WK" },
    { id: "8", name: "Ravindra Jadeja", type: "All-Rounder" },
    { id: "9", name: "Shardul Thakur", type: "Fast Bowler" },
    { id: "10", name: "Kuldip Yadav", type: "Spin Bowler" },
    { id: "11", name: "Sachin Tendulkar", type: "Batsman" },
  ],
};
  
function cricketerReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    default:
      return state;
  }
}
  
export default cricketerReducer;

Reducer2.js




const INITIAL_STATE = {
  searchFruite: "",
};
  
function searchReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    case "SEARCH_SET":
      return { ...state, searchFruite: action.searchFruite };
    default:
      return state;
  }
}
  
export default searchReducer;

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

npm start

Output: Open the browser and move to http://localhost:3000/ to view the following output.




My Personal Notes arrow_drop_up
Recommended Articles
Page :