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. 洛谷P2812 校园网络[数据加强版] [Tarjan]

    题目传送门 校园网络 题目背景 浙江省的几所OI强校的神犇发明了一种人工智能,可以AC任何题目,所以他们决定建立一个网络来共享这个软件.但是由于他们脑力劳动过多导致全身无力身体被♂掏♂空,他们来找你帮 ...

  2. mysql正则查询 模糊查询

    -- ==============正则查询================ /* SQL默认是忽略大小写的 正则模式使用REGEXP和NOT REGEXP操作符(或RLIKE和NOT RLIKE,它们 ...

  3. 八步详解Hibernate的搭建及使用

    本文通过了八个步骤以及一些实例添加用户来介绍Hibernate的搭建和使用,真切的介绍了hibernate的基本用法,其中好多优点等待我们自己去发现,比如hibernate中的缓存机制,映射方案. 1 ...

  4. poj1860 & poj2240(Bellman-Ford)

    1860的思路是将可以换得的不同种的货币的数量当作节点,每个兑换点当成边,然后我抄了个算法导论里面的Bellman-Ford算法,一次就过了.看discussion里面很多讨论精度的,我想都没想过…… ...

  5. Unity 游戏开发技巧集锦之材质的应用的创建反射材质

    Unity 游戏开发技巧集锦之材质的应用的创建反射材质 Unity中材质的应用 游戏中,大多数材质的应用都离不开纹理,而纹理本身是图片.所以,在学习本章时,最好在电脑上安装一个可以编辑图片的功能强大的 ...

  6. bzoj 3298: [USACO 2011Open]cow checkers -- 数学

    3298: [USACO 2011Open]cow checkers Time Limit: 10 Sec  Memory Limit: 128 MB Description 一天,Besssie准备 ...

  7. hdu 4114 Disney's FastPass 状压dp

    Disney's FastPass Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.ph ...

  8. 【EGit】The current branch is not configured for pull No value for key branch.master.merge found in config

    1.在当前项目的本地工程目录找到config文件(例如E:\rocket\rocket\.git): 2.修改config文件内容为: [core]    repositoryformatversio ...

  9. python模块整理29-redis模块

    date:20140530auth:jinhttp://github.com/andymccurdy/redis-pyhttps://github.com/andymccurdy/redis-py/b ...

  10. Linux下使用ping出现destination is unreachable的问题可能性

    ping时出现request time out和destination is unreachable request time out是指icmp包发出后,长时间没有回应,所以会产生request t ...