[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 ...
随机推荐
- libevent的作用或者说是有哪些功能
1. 介绍 libevent是一个用来开发可扩展的网络服务器的事件通知函数库.当一个文件描述符上的特定事件发生或是一个超时时间到达后,libevent API提供一种执行回调函数的机制.而且,libe ...
- ls 大全
ls命令是linux下最常用的命令.ls命令就是list的缩写缺省下ls用来打印出当前目录的清单如果ls指定其他目录那么就会显示指定目录里的文件及文件夹清单. 通过ls 命令不仅可以查看linu ...
- EAP-MD5认证暴力破解工具eapmd5pass
EAP-MD5认证暴力破解工具eapmd5pass EAP-MD5是一种基于802.1x协议的认证机制.由于该机制存在漏洞,所以并不能保证数据安全.Kali Linux预置一个专用工具eapmd5 ...
- socket的使用一
socket概念 socket层 理解socket Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协 ...
- 使用matplotlib绘图(一)之折线图
# 使用matplotlib绘制折线图 import matplotlib.pyplot as plt import numpy as np # 在一个图形中创建两条线 fig = plt.figur ...
- cocos2d-android 使用 cocos2d 绘图
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha cocos2d-android-1 https://github.com/ZhouWei ...
- 「UOJ207」共价大爷游长沙
「UOJ207」共价大爷游长沙 解题思路 : 快速判断两个集合是否完全相等可以随机点权 \(\text{xor}\) 的思路可以用到这道题上面,给每一条路径随机一个点权,维护出经过每一条边的点权的 \ ...
- 2017haoi总结
暴力都写不对的蒟蒻QAQ 现在只看了上午的第二题.. AM.T2 写了40分的记忆化搜索,最差复杂度大概是n^3,100以下应该是稳过的..通过递归返回[l+1,r]的答案,l=r特判,int函数 ...
- MongoDB,pymongo
MongoDB: 数据库,nosql [{ id:1 name:"蔡文姬" age: 16 gender:"女" }, { id:1 name:"蔡文 ...
- CSS的flex布局(转载)
我们之前已经学过一些布局模型,比如说浮动,绝对定位等等,但是这些布局方式一是不够简洁,而是使用的范围确实是太窄了. flex模型拥有比较多的属性,来设置多样的布局方式,接下来我们就详细介绍各种属性对布 ...