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)的更多相关文章

  1. [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 ...

  2. React & update state with props & Object.assign

    React & update state with props & Object.assign Object.assign({}, oldObj, newObj) https://re ...

  3. [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 ...

  4. [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 ...

  5. react初探(一)之JSX、状态(state)管理、条件渲染、事件处理

    前言: 最近收到组长通知我们项目组后面新开的项目准备统一技术栈为react,目前我的情况是三大框架只会angular和Vue.在实际项目中只使用过一次angular5,其余项目都是使用Vue写的.写篇 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. 【C++初级】static用法总结、问题探讨及常见错误排查

    static的基本用法: static的作用主要有两种第一个作用是限定作用域:第二个作用是保持变量内容持久化: 一.c语言中static的用法: 1.全局静态变量: 用法:在全局变量前加上关键字sta ...

  2. 最大流 [USACO4.2]草地排水Drainage Ditches

    Background 在农夫约翰的农场上,每逢下雨,贝茜最喜欢的三叶草地就积聚了一潭水.这意味着草地被水淹没了,并且小草要继续生长还要花相当长一段时间.因此,农夫约翰修建了一套排水系统来使贝茜的草地免 ...

  3. django常见问题小结,细节容易忽视

    中文URL:这个其实是很常识的东西,但是之前做web一直没注意过,在使用HttpResponseRedirect的时候,如果Redirect的URL中带中文的话,会报UnicodeEncodeErro ...

  4. 阿里云提示Discuz memcache+ssrf GETSHELL漏洞如何解决

    一般这个漏洞都是下面文件,source/function/function_core.php 搜索下面代码: $content = preg_replace($_G['setting']['outpu ...

  5. HDU 6194【后缀数组】

    题目链接[http://acm.hdu.edu.cn/showproblem.php?pid=6194] 题意: 给你一个长度不大于1e5的字符串,然后然你判断其子串严格出现k次的子串个数. 题解: ...

  6. New Year Tree 【DFS序+线段树区间查询修改+二进制保存状态】

    题目链接[http://codeforces.com/problemset/problem/620/E] 题意:给出n个数,每个数有一个初始的颜色.由这n个数组成一颗树.有两种操作1.将以节点u为根的 ...

  7. manacher算法求最长回文子序列

    一:背景 给定一个字符串,求出其最长回文子串.例如: s="abcd",最长回文长度为 1: s="ababa",最长回文长度为 5: s="abcc ...

  8. lightoj 1306 - Solutions to an Equation 扩展的欧几里得

    思路:看题就知道用扩展的欧几里得算法做!!! 首先我们可以求出ax+by=gcd(a,b)=g的一个组解(x0,y0).而要使ax+by=c有解,必须有c%g==0. 继而可以得到ax+by=c的一个 ...

  9. bzoj 1006 弦图染色

    给定一个弦图,问最少染色数. 对于弦图的一个完美消去序列,从后往前染色,每次染可以染的最小编号的颜色,由完美消去序列的定义,序列任一后缀的点的导出子图中,由该后缀第一个元素及其邻接点导出的子图一定是完 ...

  10. python3.5: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory

    python3.5安装报错 python3.5: error while loading shared libraries: libpython3.5m.so.1.0: cannot open sha ...