[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 ...
随机推荐
- ZOJ 3613 Wormhole Transport
斯坦纳树,$dp$. 先求出每个状态下连通的最小花费,因为可以是森林,所以$dp$一下. #include<bits/stdc++.h> using namespace std; int ...
- Django实现单用户登录
最近由于要毕业了写论文做毕设,然后还在实习发现已经好久都没有写博客了.今天由于工作需求,需要用Django实现单用户登录.大概意思就是跟QQ一样的效果,每个账号只能一个地方登录使用,限制账号的登录次数 ...
- svm常用核函数介绍
这里有一篇博文介绍了,每个核函数的用途: https://blog.csdn.net/batuwuhanpei/article/details/52354822 在吴恩达的课上,也曾经给出过一系列的选 ...
- 用于解析通过JS的escape函数加密过的数据
function js_unescape($str) { $ret = ''; $len = strlen($str); for ($i = 0; $i < $len; $i++) { if ( ...
- javascript入门教程笔记
BOM BOM 是“ Browser Object Model ”的缩写,简称“ 浏览器对象模型 ”. BOM 定义了 JavaScript 操作浏览器的接口,提供了访问某些功能(如浏览器窗口大小.版 ...
- 【BZOJ 3160】 3160: 万径人踪灭 (FFT)
3160: 万径人踪灭 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 1440 Solved: 799 Description Input Outp ...
- uoj386 【UNR #3】鸽子固定器
link (似乎很久没写题解了) 题意: n个物品,每个物品有a,b两个值,给定A,B,现在最多选其中m个,要求最大化选出的物品中[b权值和的B次方-a极差的A次方]. $n\leq 2\times ...
- bzoj 1231: [Usaco2008 Nov]mixup2 混乱的奶牛 -- 状压DP
1231: [Usaco2008 Nov]mixup2 混乱的奶牛 Time Limit: 10 Sec Memory Limit: 162 MB Description 混乱的奶牛 [Don Pi ...
- URAL 1995 Illegal spices 贪心构造
Illegal spices 题目连接: http://acm.timus.ru/problem.aspx?space=1&num=1995 Description Jabba: Han, m ...
- Codeforces Round #346 (Div. 2) F. Polycarp and Hay 并查集 bfs
F. Polycarp and Hay 题目连接: http://www.codeforces.com/contest/659/problem/F Description The farmer Pol ...