What is a “state”?
In the era of jQuery, JS code is mixed with DOM structure, and when various processes are complex and intertwined, noodle code will be formed. When publishing and subscribing model is used, debugging will be a mess.
JQuery is imperative programming for “procedures”, and so many commands end up updating the “data” in the UI, why not just change the data?
Beijing → Shanghai, change city=” Beijing “to city=” Shanghai”. No matter the plane or train breaks down on foot, or whether we meet Wang Baoqiang on the way,
The meaning of modern front-end frameworks is the innovation of problem solving, turning commands for “processes” into descriptions of “states”.
What is a state? State is the dynamic data in the UI.
2. Status in React
React was born in May 2013. But until 2015, it’s pretty much jQuery. React 0.13.0 was released in March 2015, bringing the class component approach.
In the React Class era, the state was this.state, updated with this.setState.
To avoid confusion, React introduced the concept of “components” and “one-way data flow.” With state and components, there is naturally the transfer of state between components, commonly referred to as “communication.”
Parent-child communication is relatively simple, while the communication of deep-level and remote components relies on the layer passing of “state promotion” + props.
React then introduced Context, an official solution for “cross-level” communication between components.
But Context is really equivalent to a “state boost”, with no additional performance optimizations, and is a bit verbose to write.
To optimize performance, multiple contexts are typically added, making writing more verbose. When the project is not that complex, it is easier to pass layers on layers.
What is “state management”?
Pragmatically, “state management” addresses “cross-level” communication between components.
Of course, when using state management libraries, there are some derived mindsets about how to organize state, how to split public logic, business logic, component logic, etc., but ultimately, these are not the core reasons.
The core is to solve practical problems — to communicate. Other concepts and philosophies are not necessary.
Context didn’t work that well, React had no official best practices, and community libraries were born.
4. State management in the class era
The React Class component era is the story of Redux (and its related libraries) versus MobX.
Redux is an implementation of the React concept. MobX’s “listen” mode isn’t React enough, but it’s easy to use.
The pros and cons of Redux have been discussed too much. In short, developers care about “usage” while Redux cares about “philosophy”.
I joked earlier that Redux could have represented it in one line of code, but wrote a sleepy document for the paper specification:
createStore = (reducer, state) = > ({ dispatch: (action) = > (state = reducer(state, action)) });
Copy the code
The React state manager is a simple implementation of observer mode:
Subscribe to listeners in each component and call them again when state is updated to trigger component updates.
5. Which are Hooks?
The React Class component has the following problems:
this.state
Is an object, and every time you update a part of it, you can also add a new state to it, which makes the whole state more chaotic.- When using patterns such as higher-order components
this.props
Data sources are opaque and equally chaotic. - because
this
With the existence of magic Pointers, it’s easy to hang a bunch of things on them, call each other randomly, and the logic gets tangled up.
React introduces Hooks to address these issues:
- Breaking up the chaotic state into individual metadata.
- Provide logical sharing in place of higher-order components.
- Component no longer exists
this
.
This is an innovation of development idea and organization idea. Hooks have three strong characteristics: primitive, decentralization and algebraic effects.
- Primitive. Metadata, built from the bottom layer, makes the data structure clearer. It is also an engineering trend. Tailwind CSS, for example, is the metaddatamation of CSS.
- Decentralization. The decentralized, class era was generally a “top down” philosophy, but Hooks brought with them a strong “component autonomy” philosophy (i.e., providers are no longer necessary, component requests handle themselves). In other areas, too, decentralization is a popular concept.
- Algebraic effects. After all, Hooks can be understood as a conduit to the React core capability, exposing internal machines to the developers.
State management in the age of Hooks
Since Hooks came along, the community has not had a state manager as dominant as Redux.
Redux adds capabilities like useSelector, useDispatch, and useStore, while Facebook itself has open-source libraries like Recoil.
But Redux was old, and its early days were so Shadowed that many people’s minds were formatted to write in a cloud for a simple function.
Recoil’s rules seemed awkward, wordy and tepid.
// Recoil
atom({ key: 'textState'.default: ' ' });
useRecoilState(textState);
Copy the code
In the time of Hooks, a mysterious organization sprang up and contributed three state management libraries.
It’s CALLED PMNDRS, PMNDRS for Poimandres. pmnd.rs
“Organization”, in fact, the main developer should be one person, the master, Daishi Kato. github.com/dai-shi
These libraries are Zustand, Jotai, and Valtio. Interestingly, all three of these words actually mean “state”.
Zustand 🇩🇪 German “status”, Jotai 🇯🇵 Japanese “status”, Valtio 🇪 Finnish “status”.
A quick look at usage:
// Zustand 🇩🇪 - Redux philosophy, old zeitgeist, centralized logic
const useStore = create((set) = > ({
bears: 0.removeBears: () = > set({ bears: 0})}));const bears = useStore((state) = > state.bears);
Copy the code
// Jotai 🇯🇵 - Primitive concept, a bit wordy but in the spirit of Hooks
const countAtom = atom(0);
const [count, setCount] = useAtom(countAtom);
Copy the code
// Valtio 🇫🇮 - Proxy concept, "not too React", but easy to use
const state = proxy({ count: 0.text: 'hello' });
const snap = useSnapshot(state);
Copy the code
7. Greedy updates vs. lazy updates?
As mentioned earlier with MobX, the proxy “listen” approach, while not quite React, is simple and intuitive.
React is essentially a “greedy update” strategy, fully re-render and then diff.
Proxy is a “lazy update” strategy, knowing exactly which variable is being updated. So using proxy, you can do some performance optimization of Re-render.
React Forget introduced in the React CONF shows that React does not reject the idea of lazy update.
Note that the “greedy update” and “lazy update” above are my own words, referencing the concepts of greed and inertia in re.
React Status management changes
- All states in a large object → split into metadata
- Data opacity → Data transparency
- Top-level request, sending data → component processes the request itself
- Status promotion → Component autonomy
- Provider & Container components → just Hooks
- Chaotic set → transparent decoupling
- Greedy update → lazy update
- Large and complete, strong concept, DX ❌ → clearer, simpler, DX ✅
- Less conceptual, more intuitive
- Less rules, more automation
In general, this is a change in the way we think about state management, but also a change in the way we think about React community development, a constant exploration of best practices:
- Decentralization
- Data set → metadata
- Build a structure, completely from the ground up
Resso is probably the simplest React state manager
I have been thinking about which React state manager is the easiest to use and constantly exploring a tool that is the most comfortable for me to use.
Retalk (Redux best practices), FLOOKS (Hooks state management) have been developed before, but with the emergence of new ideas, some of the latest inspiration is now in the Resso state management library.
Here’s how resso is used:
import resso from 'resso';
const snap = resso({ count: 0.text: 'hello' });
function App() {
return (
<>
{snap.count}
<button onClick={()= > snap.count++}>+</button>
</>
);
}
Copy the code
GitHub address: github.com/nanxiaobei/…
Note that it’s also a little easier to write than valtio, which is very simple, and it can’t be any easier, so let me know if it is.
More importantly, Resso automatically optimizes re-render and never triggers additional re-render just because the data is in the same object.
State management is a simple thing, but tools like Redux add too much complexity. The primary reason people use a tool is to solve a problem.
So, simple, clear, get tools back to tools. The way we know about a hammer is to pick it up and use it.
Hopefully, Resso will appeal to those who need it.
10. Invest the future
But what was the use of all this?
It’s not like class components don’t work, Redux doesn’t work, or even more fundamentally, jQuery doesn’t work, so why go after all these new things?
An abstract explanation: we should keep investing in the future.
Not just in development, in work, but in any field — “trading the number one status for resources in the form of continuous segmentation on new tracks”.
The tracks of the old world are crowded with weary wayfarers, although the New World mirage, but only the New World will jump everything.
The preceding content is shared with React State Management in 2022.
Download the PDF
Keynote download (more animations ~)