In React applications, state management is an unavoidable topic. For developers, how to gracefully manage state is more complicated than expected, and it is a real development art.

Why do YOU need state management

As we all know, the React application is composed of state units. Components are the core of the React application, and states are the soul of one or more components. For a React application, components form the backbone of the application, and states are the blood that runs through the whole body, which is the key to the application’s vitality and vitality.

As applications get more complex, it can be extremely difficult to tell exactly which components require state. Consuming state through the Context API is not an easy way to store all state in the root component. However, this is not an effective solution because we need not only fine-grained control of state changes through setState, but also design state communication between components. Once poorly designed, the management of the state can become chaotic, and the change of the state can become unpredictable because there is no trace of it.

External state management Redux

Redux, the most popular state management solution in the community, provides us with a predictable state container. In Redux, the state of an application is stored in a SINGLE JS object as a single source of data that can be accessed at any time. Focusing our attention on this object eliminates development and maintenance costs elsewhere. The status of the application is read-only and cannot be changed directly. The only way to modify the state is to dispatch actions to a reducer to update the state and return a new state object to render.

Through the above convention, in Redux, every state change is traceable and documented, which is extremely important for our state management programming experience, code maintenance and later bug detection. Redux itself as a subscription publishing system, the specific internal process is as follows:

Is Redux optimal?

Redux does simplify and rationalize state management, but as a streamlined library, it has a steep learning curve, daunting functional programming concepts and confusing concepts that put off many developers. And in the actual development, the development and maintenance of Redux is also a very tedious and troublesome thing.

Shawn McKay, author of Rematch, wrote in Redesigning Redux that there are six areas Redux can be improved on, but they can be summarized as follows:

  • There are many concepts of functional programming
  • Difficult to manage boilerplate files (need to switch between Reducer, saga, and Action)
  • Processing problems asynchronously

The above problems may seem common, but they are closely related to our normal state management. Because of these problems, Redux doesn’t make us more productive, it actually makes us less productive. But Redux’s state management ideas are right, and real projects need them, too. Therefore, in order to make better use of Redux and reduce its learning and use costs, we urgently need redux-based best practices.

Best practices Dva

The more Redux is used, the more engineering problems are exposed. There are a number of solutions to Redux engineering problems in the community, but Dva is the star that shines through, being called redux-based best practices in the industry.

Dva is a lightweight package based on Redux’s existing application architecture (Redux + React-Router + Redux-Saga, etc.), helping us automate the tedious steps of the Redux architecture, such as boilerplate code maintenance, store creation, and middleware configuration. Hide the nasty, tedious, error-prone steps and configure and control them with a clean API.

There are many concepts of functional programming

These problems mainly focus on the initialization of Redux. Dva solves the problem of initialization function combination by means of object configuration, as shown in the figure below:

boilerplate

On the boilerplate, Dva only resolves the automation of the Reducer and Redux-saga boilerplate, not the action boilerplate, so this is a disadvantage of Dva.

Model is an important concept of Dva and has a great influence on the Redux community. It writes state, Reducer and SAGas of each substate under Redux together, and makes the management of Redux boilerplate clear and simple through object configuration. Here’s a simple example:

Dva divides actions into synchronous and asynchronous actions, and the processing method of synchronous action is defined in the Reducers property, which is the only place where the status can be updated. The handling of asynchronous actions is defined in the Effects property, and synchronous actions can also be dispatched.

When registering the Model, Dva will create a Reducer according to the method defined in reducers and create saga side effects according to the method defined in Effects.

Processing problems asynchronously

For the handling of asynchronous actions, Dva chooses Redux-Saga. Redux-saga makes it easier to manage side effects, perform more efficiently, test more simply and deal with failures more easily. Defining asynchronous methods to handle with the generator makes asynchronous processes easier to read and write, and makes it easy to test asynchronous processes and keep actions pure.

Plug-in mechanism

While addressing Redux engineering issues, Dva provides a flexible plug-in mechanism that allows developers to drill down into every part of Redux data flow processing, further increasing code flexibility and productivity.

Is Dva perfect?

Even though it is regarded as the best practice, Dva still has the following shortcomings due to objective factors and limitations:

  • According to the personal maintenance projects, almost all of them are contributed by the authors. They failed to react accordingly to the current popular technologies (such as React Hook) and have not provided new functional updates for a long time
  • Dva is not zero boilerplate Redux best practice, there are stillactionTypes.actionCreatorsRelated maintenance

Upstart Rematch

After Dva, there were a number of state management frameworks based on Redux encapsulation, but most of them had significant limitations or even backwardness until Rematch came along. Rematch is a DVA-inspired, zero Boilerplate Redux practice, similar in style to the Vuex.

Rematch also adopts the configuration + Model scheme to encapsulate redux’s practices more simply. There are some design differences between Rematch and Dva. Let’s take a look at a complete example:

The difference between Rematch and Dva is that Rematch is just a state management framework. It is only responsible for state management and nothing else. There are not many built-in libraries. There are fewer steps to create applications, fewer unnecessary procedural calls, and the ability to never call functions through configuration.

In terms of overall usage style, Rematch is more portable. Redcuer, Saga and Action are maintained using model in a unified manner. The definition of Redcuers is combined into one. The corresponding actionCreator and actionType can be defined. Meanwhile, actions can be directly distributed through object attribute access, which reduces boilerplate code and greatly reduces our code cost.

On asynchronous issues, Rematch uses async/await instead of redux-Saga and Thunk schemes, reducing the cost of understanding and using asynchronous action processing.

In terms of plug-in ecology, Rematch has a relatively strong concept of plug-in ecology, integrating the commonly used reselect, Persist, immer and so on into plug-ins. There is room for further development in data caching, performance optimization, and development experience optimization. After all, embracing the plug-in ecosystem is a good development direction.

Better frame tang knife

From Redux to Dva to Rematch, we can see the evolution of Redux development from slash-and-burn to automation, making state management simple and efficient, but at the end of the day, the best practice is basically encapsulating Redux, Provide a simpler API without losing any configurability features.

When we see the progress of the community, we also feel a sense of helplessness. But where? It looks so good and efficient, but there is a big gap in migrating from the existing state management framework to the new one. For example, if we want to switch from Redux’s existing application architecture (Redux + React-Router + Redux-Saga) to Rematch, we must abandon Redux-Saga and change our original asynchronous processing scheme, which has a large migration cost. As a result, new projects are now automated and old projects are dead weight. This is neither what we want nor what we want to see.

Inspired by Dva, Rematch has encapsulated Redux to the extreme, but it is only the solution to Redux engineering problems, and there is still objective room for optimization in the actual state management business code, such as batch creation of action processing methods.

Tang dao

To enable as many projects (old and new) to use the same state management framework as Rematch, and to maximize the efficiency and cost of research and development, we decided to rebuild a state management framework based on Redux.

Our Maoyan front end team has conducted a long time of investigation and analysis on the existing community schemes combined with the actual situation, and decided to retain the existing application architecture of Redux (Redux + React-Router + Redux-Saga) to achieve low learning and start-up costs. Can coexist with native Redux data flow management, Dva state management framework seamless migration, rematch fast migration target. React Hook will be included in the follow-up planning to build the surrounding ecology of state management based on React Hook version and further improve the state management ability.

After a long time of development and many times of optimization, we finally created a state management framework — Tang Dao, which meets the above requirements and has certain optimization in the business code.

Tang Dao is a data flow management tool that absorbs the essence of Dva and Rematch. It achieves zero Boilerplate, rich plugin ecology, and can coexist with the original Redux data flow management mode. Dva project seamless migration, Rematch project fast migration. Considerable optimization has been made on the business code, which greatly improves the efficiency of state management. Let’s look at a complete example of Tang Dao:

In order to achieve the seamless transfer of Dva projects, Tang Tang basically keeps the same design concept and API design with Dva. The translation supports the core functions of Dva, and fixes and supplements the deficiencies of Dva to reduce the learning and starting costs of Dva users. Rematch is used for reference in sample management and action distribution, which provides the possibility and guarantee for Dva project and REmatch project to migrate to Tang Dao quickly.

Generator versus async/await

In the framework’s high encapsulation, Generator and async/await are syntactic differences for the user, written differently but functionally the same, and sagas side effects are created internally without the developer being aware of them. Therefore, for rematch users, this part is written differently and does not require much change, but nothing else.

Initialize the

In order to coexist with the Redux data flow management approach, tang Knife provides properties to configure the various tools in the Redux architecture during initialization. So can reach first access, after the transformation of the situation. Details are as follows:

With attribute configuration, you don’t have to care and understand the actual invocation process of these attributes, ensuring the possibility of fast access to projects.

The plug-in

Tang Dao is also actively embracing the plugin ecosystem. In the future, we are planning to build a surrounding ecosystem based on React Hook rich data flow management. At present, Tang Dao provides the following built-in plug-ins:

  • The loading plug-in allows you to customize the status of asynchronous and delayed asynchronous requests
  • The effectThunk plugin returns promises when sending asynchronous actions, allowing you to get the results of an asynchronous request in one step
  • The nextTick plug-in can perform deferred callbacks after the next DOM update cycle ends. Use this method immediately after the action is dispatched to get the updated DOM and the latest store.state

In the state management of the related business code, for the same writing method, just update the properties of different action processing method, Tang Dao provides batch creation of action processing method properties, let your model code thinner, less to write more code. Details are as follows:

From the above comparison, it can be seen that Tang Dao not only simplifies and makes state management efficient, but also takes into account the migration of existing schemes as much as possible, so that as many projects embrace simple and efficient state management as possible. In this process, we didn’t cheapen anything, we tried to embrace the simple philosophy behind Redux with lower learning costs, less boilerplate code, and less learning costs.

If you’re still struggling with the Redux architecture or any other state management tool, try tang Dao. It may bring you unexpected benefits.

Finally finally, xiaobian sell oneself for star, little brother miss sisters give me some of it! Github:github.com/MaoYanTech/…