React in action: Redux application architecture

Modern applications must do more than ever, and correspondingly more complex—both internally and externally. Developers have long been aware of the chaos caused by the growth of complex applications that lack consistent design. Spaghetti-like code is not only not fun, but also slows down the development progress of developers, which in turn slows down the progress of business units. Remember the last time you worked in a large code base full of disposable solutions and jQuery plugins? It is estimated that this will not be interesting. In order to combat confusion, developers have developed a paradigm such as MVC (Model-View-Controller) to organize application functions and guide development. Flux (and its extension Redux) is the same, all to help developers deal with the increasing complexity of applications.

If you are not particularly familiar with the MVC paradigm, don't worry, we won't spend much time discussing it in this book. But for the sake of comparison, before discussing Flux and Redux, let's briefly discuss MVC. Here are some basic knowledge.

  • Model (model)-application data. Usually nouns like User, Account or Post. The model should at least have basic methods for manipulating the associated data. In the most abstract sense, a model represents raw data or knowledge. The model is where data interacts with application code. For example, the database may store attributes such as accessScope, authenticated, etc. The model can use these data in methods such as isAllowedAccessForResource() on it, and these methods will operate on the underlying data of the model. The model is where the original data and application code converge.
  • View-Representation of the model. The view is usually the user interface itself. There should not be any logic in the view that has nothing to do with data representation. For front-end frameworks, this usually means that a particular view is directly associated with the resource and has CRUD (create, read, update, delete) operations associated with it. Front-end applications are no longer always built this way.
  • Controller (controller)-The controller is the "glue" that binds the model and the view together. Controllers should generally be just glue and do nothing more (for example, they should not contain complex views or database logic). Generally speaking, the ability of controllers to modify data should be much lower than the models they interact with.

Although the paradigm (Flux and Redux) discussed in this chapter is very different from these concepts, the goal is to help developers create scalable, reasonable and effective application architectures.

The origin and design of Redux is due to a popular model called Flux within Facebook. If you are familiar with the popular MVC pattern used by Ruby on Rails and other application frameworks, then Flux may be different from the pattern you are used to. Flux does not decompose the various parts of the application into models, views and controllers, but defines several different parts.

  • store-store contains the state and logic of the application. It is a bit like the model in traditional MVC. However, they manage the state of many objects instead of representing a single database record. Unlike the model, developers can represent data in any reasonable way without being restricted by resources.
  • Action-Flux applications do not directly update the state, but modify the application state by creating actions that modify the state.
  • view-user interface, usually React, but Flux doesn't need React.
  • dispatcher-a centralized coordinator for operating and updating the store.

Figure 10-1 shows an overview of Flux.

React in action: Redux application architecture

 

Figure 10-1 A simple Flux overview

As shown in Figure 10-1, in the Flux mode, the action is created from the view (maybe the user clicks on something), and then the dispatcher processes the incoming action, and then sends the action to the appropriate store for update status. After the state changes, the notification view should use the new data (if applicable). Please note how this is different from a typical MVC style framework. In an MVC style framework, both the view and the model (such as the store here) can update each other. This bidirectional data flow is different from the more unidirectional data flow that is typical in the Flux architecture. In addition, please note the lack of middleware here: although middleware can be created in Flux, it is not a first-class citizen like in Redux, so we omit it here.

If you have developed an MVC style application before, some of the content sounds familiar, but the data flow method may not be the case. As mentioned earlier, data flows more in one direction in the Flux paradigm, which is different from the two-way way that MVC-type implementations tend to use. This usually means that there is no single source of data flow in the application; many different parts of the system have the right to modify the state, and the state is usually scattered throughout the application. This method works well in many situations, but in larger applications, debugging and use may be confusing.

Imagine what this would be like in a medium to large application. Suppose there is a set of models (users, accounts, and authentication) that are associated with their own controllers and views. Anywhere in the application, it is difficult to determine the exact location of the state, because the state is distributed in various parts of the application (information about the user can be found in any of the 3 models mentioned earlier).

For smaller applications, this may not necessarily be a problem, and may even work well on larger applications, but in large client applications, it may become more difficult. For example, what happens when the use of the model needs to be modified in 50 different locations and there are 60 different controllers that need to be aware of the state change? To make things more complicated, the view sometimes behaves like a model in some front-end frameworks (so the state is more dispersed). Where is the true source of the data? If it is scattered across views and many different models, and all of them are in a moderately complex setting, it will be difficult to keep track of everything in mind. This may also lead to inconsistencies in the application state, which will cause application bugs. Therefore, this is not just a problem that "only developers face", end users will also be directly affected.

Part of the reason this is difficult is that people are generally not good at inferring changes over time. In order to truly understand this question, imagine a chessboard in your mind. It’s not difficult to keep a snapshot of a chessboard or even a few in your head, but can you keep track of every chessboard snapshot for 20 rounds? What about round 30? How about the whole game? Because it is difficult to track the asynchronous changes of data over time in our minds, we should build systems that are easier for us to think and use. For example, consider calling a remote API and using its data to update the application state. This is simple for a small number of cases, but if you need to call 50 different API server endpoints and need to track incoming responses, while the user is still using the application and making changes that may cause more API interactions, What will happen then? It is difficult to sort them out in your mind and predict the outcome of changes.

You may have noticed some similarities between React and Flux. They are both relatively new ways of building user interfaces and both aim to improve the mental models used by developers. In these two ways, changes should be easy to infer, and developers should be able to build the UI in a way that enhances rather than interferes.

What does Flux look like in actual code? It is mainly a paradigm, so there are many libraries that implement the core idea of ​​Flux. These libraries are slightly different in the way they implement Flux. Redux is the same, although its unique Flux style has gained the most users and attention. Other Flux libraries include Flummox, Fluxxor, Reflux, Fluxible, Lux, McFly, and MartyJS (although in practice these libraries are rarely used compared to Redux).

10.1.1 First encounter with Redux: a variant of Flux

Perhaps Redux is the most widely used and well-known library that implements the ideas behind Flux. The Redux library implements the idea of ​​Flux in a slightly modified way. The Redux documentation describes it as a "predictable state container for JavaScript applications." Specifically, this means that it puts Flux's concepts and ideas into practice in its own way.

It is not important to determine the exact definition of Flux here. What is important is that I will introduce some important differences between Flux and Redux paradigms.

  • Redux uses a single store-Redux applications do not store state information in multiple stores in the application, but save everything in one place. Flux can have multiple different stores. Redux breaks this rule and enforces the use of a single global store.
  • Redux introduces reducers-reducers make changes in a more immutable way. In Redux, the state is changed in a deterministic and predictable way, only a part of the state is modified at a time, and it only occurs in one place (in the global store).
  • Redux introduces middleware-because actions and data flow are one-way, developers can add middleware to Redux applications and inject custom behaviors when data is updated.
  • Redux's actions are not coupled to the store-the action creators will not dispatch anything to the store; instead, they will return the action object used by the central scheduler.

For you, these may be just nuances, it doesn't matter-your goal is to learn Redux, not to "find the difference." Figure 10-2 shows an overview of the Redux architecture. We will dive into each of the different parts, explore how they work, and develop a Redux architecture for your application.

React in action: Redux application architecture

 

Figure 10-2 Overview of Redux

As shown in Figure 10-2, action, store, and reducer constitute the main body of the Redux architecture. Redux uses a centralized state object, which is updated in a specific and deterministic way. When the developer wants to update the state (usually due to events such as clicks), an action is created. Actions have types that a particular reducer will handle. A reducer that processes a given action type generates a copy of the current state, uses data from the action to modify it, and then returns to the new state. When the store is updated, the view layer (here, the React component) can listen for the update and respond accordingly. Also note that the views in the figure just read updates from the store-they don't care about the data they communicate with. The React-redux library will pass new props to the component when the store changes, but the view still only receives and displays data.

10.1.2 Preparing for Redux

Redux is an application architecture paradigm, it is also an installable library. This is one aspect of Redux over the "raw" Flux implementation. There are many implementations of the Flux paradigm (such as Flummox, Fluxxor, Reflux, Fluxible, Lux, McFly and MartyJS), and they all have different levels of community support and different APIs. Redux has strong community support, but the API of the Redux library itself is very small and powerful, which helps it become one of the most popular and most relied upon React application architecture libraries. In fact, the use of Redux with React is so common that the two core teams often communicate with each other to ensure compatibility and awareness of features. Some people are even on two teams at the same time, so there is good visibility and good communication between the two projects.

In order to set up Redux to use it, some work needs to be done.

  • Make sure to run npm install with the source code of the current chapter so that all the correct dependencies are installed locally. In this chapter, we will start to utilize several new libraries, including js-cookie, rudux-mock-store and redux.
  • Install Redux developer tools. We can use them to view Redux store and action in the browser.

Redux is designed to be predictable, which makes it easy to create amazing debugging tools. Dan Abramov and other engineers working on Redux and React libraries have developed some powerful tools for handling Redux applications. Because the state in Redux changes in a predictable way, it is possible to debug in new ways: developers can track individual changes in the application state, check the differences between changes, and even rewind and replay the application state as it changes. Time changes. The Redux Dev Tools extension allows users to complete all these tasks and even more, and it is packaged as a browser extension for distribution. Figure 10-3 provides a quick glimpse of the functions of the Redux Dev Tool.

React in action: Redux application architecture

 

Figure 10-3 The Redux Dev Tools extension packages the popular Redux Dev Tools library from Dan Abramov into a convenient browser extension. With it, you can rewind and replay Redux applications, view changes one by one, check the differences between state changes, check the state of the entire application in one area, generate test templates, etc.

After installing the extension, you should be able to see the icon of the new development tool in the toolbar of the browser. At the end of the writing period, it will only become colored when a Redux application instance is detected in development mode, so if the visited application or website does not use Redux, the extension will not work. But once the application is configured, you will see that the icon becomes colored, and clicking on it will open the tool.

This article is taken from "React Actual Combat"

React in action: Redux application architecture

This book guides the reader to think about user interfaces (UI) like an expert, and teaches the reader to build them with React. This book is very practical, with many practical examples, allowing readers to quickly get started. The goal of this book is to enable readers to master the core concepts of rendering, life cycle methods, JSX, data flow, forms, routing, integration with third-party libraries and testing, and to help readers use the application design concepts introduced in the book to promote application popularity. In the process of learning to integrate React into a full-stack application, readers can also explore state management and server-side rendering through Redu**, and even get in touch with React Native for mobile UI. This book is written specifically for developers who are familiar with HTML, CSS, and JavaScript.

The main content of this book
● Use React from scratch.
● Implement routing system with components.
● Server-side rendering in Node.js.
● Use third-party libraries.
● Test React components.

Guess you like

Origin blog.csdn.net/epubit17/article/details/107965691