[React] Use the useReducer Hook and Dispatch Actions to Update State (useReducer, useMemo, useEffect)
As an alternate to useState, you could also use the useReducer hook that provides state and a dispatch method for triggering actions. In this lesson, we’ll centralize logic that is spread across a web application and centralize it using the useReducer hook.
NOTE: Since hooks are still a proposal and only pre-released, it’s not currently recommended to use them in production.
useReducer:
const [todos, dispatch] = useReducer((state, action) => {
switch (action.type) {
case "ADD_TODO":
todoId.current += ;
return [
...state,
{ id: todoId.current, text: action.text, completed: false }
];
case "DELETE_TODO":
return state.filter(todo => todo.id !== action.id);
case "TOGGLE_TODO":
return state.map(todo =>
todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
);
default:
return state;
}
},initialValue);
useReducer can accept second param as a function, so we can replace 'initialValue' with a function return a 'initialValue', which means we can using cache for the function if the param doesn't change, we always return the cache. To do that we can use
useMemo:
const [todos, dispatch] = useReducer((state, action) => {
switch (action.type) {
case "ADD_TODO":
todoId.current += ;
return [
...state,
{ id: todoId.current, text: action.text, completed: false }
];
case "DELETE_TODO":
return state.filter(todo => todo.id !== action.id);
case "TOGGLE_TODO":
return state.map(todo =>
todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
);
default:
return state;
}
}, useMemo(initialValue, []));
The second parameter of 'useMemo' indicates when the memorized version should change. In our case, we want it to always be the same, so passing an empty array conveys that message.
To handle side effect of action, in our case, is update localstorage, we can use useEffect:
useEffect(
() => {
window.localStorage.setItem("todos", JSON.stringify(todos));
},
[todos]
);
---
[React] Use the useReducer Hook and Dispatch Actions to Update State (useReducer, useMemo, useEffect)的更多相关文章
- [React] Update State Based on Props using the Lifecycle Hook getDerivedStateFromProps in React16.3
getDerivedStateFromProps is lifecycle hook introduced with React 16.3 and intended as a replacement ...
- React & update state with props & Object.assign
React & update state with props & Object.assign Object.assign({}, oldObj, newObj) https://re ...
- [React + Functional Programming ADT] Create Redux Middleware to Dispatch Actions with the Async ADT
We would like the ability to group a series of actions to be dispatched with single dispatching func ...
- [React] Use react-rewards to add microinteractions to React app to reward users for some actions
It's important that our users enjoy using our application or website. One way we can make it happen ...
- react初探(一)之JSX、状态(state)管理、条件渲染、事件处理
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技术栈为react,目前我的情况是三大框架只会angular和Vue.在实际项目中只使用过一次angular5,其余项目都是使用Vue写的.写篇 ...
- [React] Call setState with null to Avoid Triggering an Update in React 16
Sometimes it’s desired to decide within an updater function if an update to re-render should be trig ...
- [Nuxt] Update State with Vuex Actions in Nuxt.js
You can conditionally add classes to Vue.js templates using v-bind:class. This will help display the ...
- [React] Update State in React with Ramda's Evolve
In this lesson we'll take a stateful React component and look at how we can refactor our setState ca ...
- [React] Use CSS Transitions to Avoid a Flash of Loading State
Based on research at Facebook, we know that if a user sees a flash of loading state, they perceive t ...
随机推荐
- 洛谷P3292 [SCOI2016] 幸运数字 [线性基,倍增]
题目传送门 幸运数字 题目描述 A 国共有 n 座城市,这些城市由 n-1 条道路相连,使得任意两座城市可以互达,且路径唯一.每座城市都有一个幸运数字,以纪念碑的形式矗立在这座城市的正中心,作为城市的 ...
- python3 怎么爬取新闻网站?
先开个坑,以后再填吧....... import requests from bs4 import BeautifulSoup def content(url): text = requests.ge ...
- 学点编码知识又不会死:Unicode的流言终结者和编码大揭秘
如果你是一个生活在2003年的程序员,却不了解字符.字符集.编码和Unicode这些基础知识.那你可要小心了,要是被我抓到你,我会让你在潜水艇里剥六个月洋葱来惩罚你. 这个邪恶的恐吓是Joel Spo ...
- Linux下对拍脚本
使用说明: 1. 被测代码.正确代码.生成器代码均使用文件输入输出: 2. 对拍前会清屏,请注意: 3. 输出文件的文件名请和代码文件名保持一致: 4. 若无 ...
- 欧拉路小结 JZYZOJ1210 骑马修栅栏
现在写到欧拉路,理解起来并不算特别困难...吧... 但是非常恶心的是每次都要调试半天,做不到一遍两遍就能ac 每次写程序都对于程序的整体构架没有清晰的思路,想到哪里写到哪里真的是个非常差的习惯[尽管 ...
- 用ExifInterface读取经纬度的时候遇到的一个问题
如果读取图片经纬度,使用 String latValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE); String ln ...
- 解决Android-studio假死机建议
背景 终于第一个ios app发布应用商店送审了,这下也有时间把以前写的android更新一版,但是很久没遇到的as假死机问题又各种折腾了一天..最终解决的方法实在是让人忍无可忍,实在是想写下来给那些 ...
- CentOS 6.9/7通过yum安装指定版本的Node.js
说明:通过yum好处其实很多,环境变量不用配置,配置文件放在大家都熟悉的地方,通过rpm -ql xxx可以知道全部文件的地方等等. Node.js(8.x) 一.安装和配置 1.安装Node.js ...
- mysql中日期比较大小的方法
假如有个表product有个字段add_time,它的数据类型为datetime,有人可能会这样写sql: select * from product where add_time = '2013-0 ...
- Spring EL bean引用实例
在Spring EL,可以使用点(.)符号嵌套属性参考一个bean.例如,“bean.property_name”. public class Customer { @Value("#{ad ...