iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
❓

What is State Management?

に公開
2020/10/09
1件

What is "State Management"?

"State management" is a term that flies around the frontend community quite frequently. However, I suspect there are many people who honestly feel like they have no idea what it actually means.

State management is a term born from the unique circumstances of frontend development. Since it is a conceptual theme related to architecture, it gives an intimidating impression to frontend beginners, especially those just starting out as engineers. In this article, I would like to explain "state management" in a way that is easy to understand for those people.

Target Audience

Engineers who don't have a clear idea of what state management means.

TL;DR

In my interpretation, "state management" is a theme that inevitably arises when implementing UIs in a stateless manner during SPA development: "So, where and how do we hold the state?"

Complexity in SPA Development Stems from "State"

Traditional frontend development was a "simple job" of just converting data into static HTML

A while back, it was common to use technologies called template engines (like JSP or Blade) for building views. Their job was to convert data into HTML by making full use of loops, conditional branching, and variable embedding.

@foreach($users as $user)
<div>
  {{$user->getUsername()}}
<div>
@endforeach

In the Blade (Laravel) example above, the UI is built by receiving $user as an argument, iterating with @foreach, and embedding the variables inside {{}}. It's simple. (Excluding the problem of having to learn the syntax of different template engines for each backend MVC framework). This is because UI construction is completed only by functional processing, taking data and templates as input and outputting HTML.

SPAs where the UI continues to change dynamically on the user's browser

Now, the trend in recent frontend development is SPA (Single Page Application). Unlike traditional functional UI construction, this forced developers to face the problem of "UI transitions", where the UI continues to change dynamically on the user's browser. For example, UI transitions occur in cases like the following:

  • Fetching data asynchronously from the server
  • Real-time form validation
  • Switching tabs within a page

Why does "UI transition" create complexity?

Why does "the UI continuing to change dynamically" create complexity? It is because, in order to change the UI, you must keep touching the state of the previous DOM. Let's look at a sample implementation of fetching data asynchronously from the server with vanilla JS.

// Fetch data from an API
const getTodoList = async () => {
  return ["Play", "Shopping", "Homework"];
};

const container = document.getElementById("todo-list");

// Display a loading screen
const loading = document.createElement("div");
loading.textContent = "loading";
container.appendChild(loading);

getTodoList().then(todoList => {

  // Remove the loading screen
  container.removeChild(loading);

  todoList.forEach(todo => {
    const dom = document.createElement("li");
    dom.textContent = todo;
    container.appendChild(dom);
  });
});

The troublesome part is that when displaying the actual TODO list from the loading screen, you have to delete the loading screen. Also, while we are displaying the TODO list in <div id="todo-list" />, there is no guarantee that <div id="todo-list" /> exists in the DOM. In SPA development, it is assumed that the UI will always change rapidly due to many asynchronous processes. "Continuing to touch the state of the previous DOM" forces addition and subtraction of the DOM. This results in logic being tightly coupled to the UI. This remains the same even if you use simple DOM manipulation helpers like jQuery.

The Frontend Succeeded in Completely Decoupling that Complexity from Markup

React (and other recent view libraries) solved this complexity. React keeps Declarative as a concept (https://reactjs.org/), making it possible to implement UI construction as a "function that converts data to HTML" as shown in the example below.


// Fetch data from an API
const getTodoList = async () => {
  return ["Play", "Shopping", "Homework"];
};

// Custom hook
const useTodoList = () => {
  const [state, setState] = React.useState<string[] | null>(null);
  React.useEffect(() => {
    getTodoList().then(todoList => {
      setState(todoList);
    });
  }, []);
  return state;
};

function App() {
  const state = useTodoList();
  // A function that displays loading if data hasn't been fetched yet, or displays it if it has
  return <ul>{state ? state.map(e => <li>{e}</li>) : "Loding"}</ul>;
}

What is Declarative UI Construction?

What does "declarative" mean in UI construction as advocated by React? As mentioned earlier, it can be interpreted as implementing it as a "function that converts data to HTML." In other words, when doing markup, you only need to focus on how to represent the current data given as an argument as HTML. You no longer need to worry about "UI transitions," such as what state the DOM was in the past.

The Problem Moves from "UI Transitions" to "Data Transitions," and then to the Term "State Management"

Markup was freed from "UI transitions" and became easier.

However, this only separated "state" from "markup"; the frontend is never freed from "state." You will still be troubled by "data transitions." The frontend community thematized this problem with the word "state management," which led to the birth of tools for state management such as Flux and Redux.

Trash Diagram.jpg

The Significance of Managing "State"

Of course, it is possible to develop using React or Vue without knowing the word "state management" and without using state management libraries. However, in team-scale development, if there is no consistent policy for state management in the application, developers will have to rack their brains from scratch about "state management," and the resulting source code will likely be difficult to understand, with state code and markup code mixed together. On the other hand, if you can perfectly manage state, you will be able to control the communication between the user and the domain exactly as you wish. This is because state is the "source" of information that users get from the application and is the Single source of truth for the user.

Discussion

______

なるほど。良い記事でした。ありがとうございます!
jQuery が衰退して、React等が台頭してきたのは
view の生成を宣言的・関数的に行えることなんですね。

3