[React] Refactor a connected Redux component to use Unstated
2024-08-22 20:18:56
In this lesson, I refactor a simple Counter component connected to Redux to use Unstated instead. I explain some of the cognitive overhead of working with Redux and how Unstated can help simplify your application codebase.
Additional Resources https://github.com/jamiebuilds/unstated
A basic example for Unstated:
/**
* Unstated Example
*/
import React from "react";
import ReactDOM from "react-dom";
import Counter from "./components/Counter";
import { Provider, Subscribe, Container } from "unstated"; class CounterContainer extends Container {
state = {
count: 0
}; increment() {
this.setState({ count: this.state.count + 1 });
} decrement() {
this.setState({ count: this.state.count - 1 });
}
} const ConnectedCounter = () => (
<Subscribe to={[CounterContainer]}>
{counter => (
<Counter
value={counter.state.count}
onIncrement={() => counter.increment()}
onDecrement={() => counter.decrement()}
/>
)}
</Subscribe>
); ReactDOM.render(
<Provider>
<ConnectedCounter />
</Provider>,
document.getElementById("root")
);
We use:
<Subscribe to={[CounterContainer]>
I means we want to keep the state for the component itself.
We can do some interesting things with <Provider>
as well like dependency injection:
let counter = new CounterContainer(); render(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
最新文章
- Mac OSX网络诊断命令
- 【转】nginx中的ngx_cdecl
- SQL Server 2008 R2——VC++ ADO 操作 重复利用_ParameterPtr
- 查看mysql版本的四种方法
- junit中的assert方法总结
- Centos7.5 java环境的安装配置
- 【已解决】Android ADT中增大AVD内存后无法启动:emulator failed to allocate memory 8
- 使用Windbg和SoS扩展调试分析.NET程序
- 无递归 A星寻路算法
- C++拾遗(二)关于变量
- gcc #define 学习记录
- android Fragment 用法小结
- iis虚拟目录或应用程序不继承父站点的web.config配置信息
- Javascript之学习笔记每日更新
- xCode8以及iOS10 的新特性
- R语言︱机器学习模型评价指标+(转)模型出错的四大原因及如何纠错
- nodejs常见问题
- 微信小程序调用地图选取位置后返回信息
- Luogu 2680 NOIP 2015 运输计划(树链剖分,LCA,树状数组,树的重心,二分,差分)
- Revit API创建一个拷贝房间内对象布局命令