Open In App

What are the three principles that Redux follows ?

Last Updated : 17 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Redux was developed to help front-end developers write applications for consistent behavior. 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.

Prerequisites:

Three principles that Redux follows are:

  • Redux is a Single Source of Truth
  • The State is Reada only State
  • The Modifications are Done with Pure Functions

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

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.

The State is Read-only State:

There is only one way to change 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.

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.

Steps to create React Application and 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 i redux react-redux

Project Structure:

The updated dependencies in package.json file.

"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-redux": "^8.1.3",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"web-vitals": "^2.1.4"
},

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.

Javascript




// Filename - 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);


Javascript




// Filename - reducers/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;


Javascript




// Filename - reducers/searchReducer.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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads