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. hihocoder 1490 Tree Restoration

    构造. 从最后一层开始往上构造.最后一层肯定都是叶子结点,距离为2的肯定是同一个父亲,确定好了父亲之后,可以确定上一层每个节点之间的距离,以及上一层每个节点到还未确定的叶子节点之间的距离. #incl ...

  2. Spring框架中ModelAndView、Model、ModelMap区别 (转)

    原文地址:http://www.cnblogs.com/google4y/p/3421017.html SPRING框架中ModelAndView.Model.ModelMap区别   注意:如果方法 ...

  3. 二进制拆位(贪心)【p2114】[NOI2014]起床困难综合症

    Description 21世纪,许多人得了一种奇怪的病:起床困难综合症,其临床表现为:起床难,起床后精神不佳.作为一名青春阳光好少年,atm一直坚持与起床困难综合症作斗争.通过研究相关文献,他找到了 ...

  4. 管理lvm 卷 system-storage-manager

    安装 sudo yum install system-storage-manager [root@si-test-blueking--4 ~]# ssm list 创建物理磁盘到物理卷,<poo ...

  5. [USACO06FEC]Milk Patterns --- 后缀数组

    [USACO06FEC]Milk Patterns 题目描述: Farmer John has noticed that the quality of milk given by his cows v ...

  6. 记一次初步Linux提权

    前言. 提权这么久了  还是头一次提下Linux的服务器... 由于之前一直钻研的win服务器  要不是前些日子爆出来Struts2-045漏洞 估计还没时间接触Linux提权.... 正文. st2 ...

  7. NSDictionary , NSMutableDictionary, NSMutableDictionary 和 NSMutableSet)相当于java的map、set

    1 NSDictionary 和 NSMutableDictionary NSDictionary  :就是java中的map; 放入对象是键值对 key-value  , 同样 秉持了一样的原则,只 ...

  8. HDU 4690 EBCDIC (2013多校 1005题 胡搞题)

    EBCDIC Time Limit: 2000/2000 MS (Java/Others)    Memory Limit: 102400/102400 K (Java/Others)Total Su ...

  9. Fully Digital Implemented Delta-Sigma Analog to Digital Converter

    http://www.design-reuse.com/articles/14886/fully-digital-implemented-delta-sigma-analog-to-digital-c ...

  10. JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式

    JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 它基于JavaScript(Standard ECMA-262 3rd Edition - D ...