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. SCU 4443 Range Query

    二分图最大匹配,枚举. 可以计算出每一个位置可以放哪些数字,每个数字可以放在哪些位置,这样就可以建二分图了. 如果二分图最大匹配不到$n$,则无解.否则构造字典序最小的解,可以枚举每一位放什么数字,然 ...

  2. 洛谷P2231 [HNOI2002]跳蚤 [数论,容斥原理]

    题目传送门 跳蚤 题目描述 Z城市居住着很多只跳蚤.在Z城市周六生活频道有一个娱乐节目.一只跳蚤将被请上一个高空钢丝的正中央.钢丝很长,可以看作是无限长.节目主持人会给该跳蚤发一张卡片.卡片上写有N+ ...

  3. IDC、ICP、ISP区别

    ICP( Internet Content Provider):网络内容服务商,即向广大用户综合提供互联网信息业务和增值业务的电信运营商.其必须具备的证书即为ICP证,如运营一个网站,需要进行备案获取 ...

  4. Linux中mysql的操作

    一.mysql服务操作 二.数据库操作 三.数据表操作 四.修改表结构 五.数据备份和恢复 六.卸载数据库

  5. 腾讯后台研发暑期实习offer经历

    昨晚看到腾讯校招的微信状态,一颗心终于落下来了,终于可以去梦寐以求的鹅厂工作了.想想这一个多月以来,心情就像过山车一样,此起彼伏,一会充满希望,一会又跌入谷底. 三月份的时候,听说腾讯可以内推了,我内 ...

  6. LruCache 原理

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha LruCache 使用一个 链表式的哈希图LinkedHashMap 简单的实现 内存的 ...

  7. python3-开发进阶Flask的基础(4)

    今日内容: 上下文管理:LocalProxy对象 上下文管理:  请求上下文: request/session   app上下文:app/g 第三方组件:wtforms       1.使用      ...

  8. 没有调用PageHelper.startPage()分页方法,最后还是执行了PageHelper分页方法的原因

    SELECT * FROM ( SELECT TMP_PAGE.*, ROWNUM ROW_ID FROM ( SELECT * FROM ( SELECT A.*, ROWNUM RN FROM ( ...

  9. 测试用例设计——WEB通用测试用例(转)

    http://qa.blog.163.com/blog/static/190147002201111332029404/

  10. js中常用日期时间转换

    常用日期时间处理插件:1. timeago.js处理几分钟之前    2. day.js    3. moment.js 注意: 1. 此处的标准时间格式为  2018-03-23 13:35:47 ...