[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 ...
随机推荐
- NBUT 1221 Intermediary
最短路,三进制状态压缩. $dis[i][j]$表示到$i$节点,每个中介用了几次的情况下的最小花费,跑最短路即可. #include<cstdio> #include<cstrin ...
- 洛谷——P1894 [USACO4.2]完美的牛栏The Perfect Stall
P1894 [USACO4.2]完美的牛栏The Perfect Stall 题目描述 农夫约翰上个星期刚刚建好了他的新牛棚,他使用了最新的挤奶技术.不幸的是,由于工程问题,每个牛栏都不一样.第一个星 ...
- AppDomain.CurrentDomain.BaseDirectory是什么
AppDomain.CurrentDomain.BaseDirectory 是获取基目录,它由程序集冲突解决程序用来探测程序集.由显示的路径可以看出,它代表的是程序集所在的目录,它具有读取和写入的属性 ...
- JS延迟执行
<!DOCTYPE html> <html> <head> <title></title> <script type="te ...
- Python操作Mongo数据库
连接数据库 import pymongo # 连接到数据库,以下两种方式均可 client = pymongo.MongoClient(host='localhost', port=27017) cl ...
- [bzoj1015](JSOI2008)星球大战 starwar(离线+并查集)
Description 很久以前,在一个遥远的星系,一个黑暗的帝国靠着它的超级武 器统治者整个星系.某一天,凭着一个偶然的机遇,一支反抗军摧毁了帝国的超级武器,并攻下了星系中几乎所有的星球.这些星球通 ...
- 37.递推:Pell数列
总时间限制: 3000ms 内存限制: 65536kB 描述 Pell数列a1, a2, a3, ...的定义是这样的,a1 = 1, a2 = 2, ... , an = 2 * an − 1 + ...
- Codeforces Beta Round #9 (Div. 2 Only) C. Hexadecimal's Numbers dfs
C. Hexadecimal's Numbers 题目连接: http://www.codeforces.com/contest/9/problem/C Description One beautif ...
- Codeforces Beta Round #5 D. Follow Traffic Rules 物理
D. Follow Traffic Rules 题目连接: http://www.codeforces.com/contest/5/problem/D Description Everybody kn ...
- MYSQL GDB SHELL
http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201141165216974/