[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 ...
随机推荐
- Python类总结-析构函数和__call__方法
class Foo: def __init__(self): pass #析构函数 def __del__(self): print('解释器要销毁我了,我要做最后一次呐喊') def __call_ ...
- Week Three
2018.12.10 1.[BZOJ 4818][P 3702] 2.[AGC007 A] 3.[AGC007 B] 4.[AGC007 C] 5.[AGC007 D] 2018.12.11 1.[B ...
- Nginx 502 Bad Gateway 解决方法
proxy_next_upstream error timeout invalid_header http_500 http_503;或者尝试设置:large_client_header_buffer ...
- java - 内存泄漏
内存泄漏问题产生原因 长生命周期的对象持有短生命周期对象的引用就很可能发生内存泄露,尽管短生命周期对象已经不再需要,但是因为长生命周期对象持有它的引用而导致不能被回收,这就是java中内存泄露的发生场 ...
- C# MATLAB混合编程
我附带把matlab配置过程也给大家上传上来.[转载]终于学会C#调用matlab函数了,原来这么简单(也可以下载附件查看)自己的配置: (1)Microsoft Visual Studio 2005 ...
- 移动应用安全开发指南(Android)--数据验证
概述 移动应用往往通过数据的发送.接收和处理来完成一系列功能,通常情况下,处理的数据绝大部分都来源于外部(比如网络.内部或外部存储和用户输入等),对这些数据处理不当会导致各种各样的漏洞和风险,比代码执 ...
- Redmine 邮件配置
高版本号的Redmine是没有email.yml的.是和configuration.yml合并了.仅仅要配置configuration.yml即可了. 首先得说下Redmine的邮件,配置这个邮件,是 ...
- HBase中的Client如何路由到正确的RegionServer
在HBase中,大部分的操作都是在RegionServer完成的,Client端想要插入,删除,查询数据都需要先找到相应的RegionServer.什么叫相应的RegionServer?就是管理你要操 ...
- promise和Rxjs的一点区别
promise 代码 let promise = new Promise( (resolve) => { setTimeout(() => { resolve('chen'); },200 ...
- InstallShield 2010集成.net Framework 4的安装包制作
InstallShield 2010中制作安装包时,对于集成.net Framework 4以前的版本,如3.5 sp1/3.5/3.0/2.0 sp2/2.0sp1/2.0等提供了现成的prq文件模 ...