[React] Preventing extra re-rendering with function component by using React.memo and useCallback
Got the idea form this lesson. Not sure whether it is the ncessary, no othere better way to handle it.
Have a TodoList component, every time types in NewTodo input fields, will trigger the re-rendering for all components.
import React, { useState, useContext, useCallback } from "react";
import NewTodo from "./NewTodo";
import TodoItem from "./TodoItem5";
import { Container, List } from "./Styled";
import About from "./About";
import { useTodosWithLocalStorage, useKeyDown } from "./hooks";
import { useTitle as useDocumentTitle } from "react-use";
import ThemeContext from "./ThemeContext";
const incompleteTodoCount = todos =>
todos.reduce((memo, todo) => (!todo.completed ? memo + 1 : memo), 0);
export default function TodoList() {
const [newTodo, updateNewTodo] = useState("");
const [todos, dispatch] = useTodosWithLocalStorage([]);
const inCompleteCount = incompleteTodoCount(todos);
const title = inCompleteCount ? `Todos (${inCompleteCount})` : "Todos";
useDocumentTitle(title);
let [showAbout, setShowAbout] = useKeyDown(
{ "?": true, Escape: false },
false
);
const handleNewSubmit = e => {
e.preventDefault();
dispatch({ type: "ADD_TODO", text: newTodo });
updateNewTodo("");
};
const theme = useContext(ThemeContext);
return (
<Container todos={todos}>
<NewTodo
onSubmit={handleNewSubmit}
value={newTodo}
onChange={e => updateNewTodo(e.target.value)}
/>
{!!todos.length && (
<List theme={theme}>
{todos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onChange={id => dispatch({ type: "TOGGLE_TODO", id })}
onDelete={id => dispatch({ type: "DELETE_TODO", id })}
/>
))}
</List>
)}
<About isOpen={showAbout} onClose={() => setShowAbout(false)} />
</Container>
);
}
The way to solve the problem is
1. For every callback:
<TodoItem
onChange={id => dispatch({ type: "TOGGLE_TODO", id })}
onDelete={id => dispatch({ type: "DELETE_TODO", id })}
/> <About isOpen={showAbout} onClose={() => setShowAbout(false)} />
We should replace with useCallback hooks:
const handleChange = useCallback(
id => dispatch({ type: "TOGGLE_TODO", id }),
[]
);
const handleDelete = useCallback(
id => dispatch({ type: "DELETE_TODO", id }),
[]
); const handleClose = userCallback(
() => setShowAbout(false), []
)
{!!todos.length && (
<List theme={theme}>
{todos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onChange={handleChange}
onDelete={handleDelete}
/>
))}
</List>
)}
<About isOpen={showAbout} onClose={handleClose} />
This helps to reduce some extra re-rendering.
2. Using Reac.memo for function component:
import React, { useContext } from "react";
import Checkbox from "./Checkbox";
import ThemeContext from "./ThemeContext";
import { Button, Item } from "./Styled";
const TodoItem = React.memo(({ todo, onChange, onDelete }) => {
console.log("TodoItem5", { todo, onChange, onDelete });
const theme = useContext(ThemeContext);
return (
<Item key={todo.id} theme={theme}>
<Checkbox
id={todo.id}
label={todo.text}
checked={todo.completed}
onChange={onChange.bind(this, todo.id)}
/>
<Button onClick={onDelete.bind(this, todo.id)} theme={theme}>
x
</Button>
</Item>
);
});
export default TodoItem;
import React from "react";
import styled from "react-emotion"; import { Dialog } from "@reach/dialog"; ... export default React.memo(function TodoItem({ isOpen, onClose }) {
return (
<Dialog isOpen={isOpen}>
...
</Dialog>
);
});
Assume that every times I should wrap function component with React.memo() and use useCallback whenever necessary.
[React] Preventing extra re-rendering with function component by using React.memo and useCallback的更多相关文章
- [React] Write a stateful Component with the React useState Hook and TypeScript
Here we refactor a React TypeScript class component to a function component with a useState hook and ...
- 精读《Function Component 入门》
1. 引言 如果你在使用 React 16,可以尝试 Function Component 风格,享受更大的灵活性.但在尝试之前,最好先阅读本文,对 Function Component 的思维模式有 ...
- [React] Preview and edit a component live with React Live
In this lesson we'll use React Live to preview and edit a component directly in the browser. React L ...
- [React] Forward a DOM reference to another Component using forwardRef in React 16.3
The function forwardRef allows us to extract a ref and pass it to its descendants. This is a powerfu ...
- 3.React Native在Android中自己定义Component和Module
React Native终于展示的UI全是Native的UI.将Native的信息封装成React方便的调用. 那么Native是怎样封装成React调用的?Native和React是怎样交互的? V ...
- React报错之React Hook 'useEffect' is called in function
正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...
- [React & Debug] Quick way to debug Stateless component
For example we have the following code: const TodoList = (props) => ( <div className="Tod ...
- react 使用react-router-dom 在Route对象上component 参数接收的是一个方法而非一个对象
其实对于jsx语法 一直觉的它有点清晰都不是很好,js和html混在一起有点不伦不类的样子,以下是我在使用react中遇到的一个很奇葩的事情 假定你定义了一个component Mine import ...
- 《React Native 精解与实战》书籍连载「React Native 底层原理」
此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...
随机推荐
- Spring boot的hot swapping
前言 嘛,都是看官方文档的,就先贴上文档地址: using-boot-hot-swapping 使用 使用hot swapping只需要把devtools的jar包添加到你的classpath里. 在 ...
- Lambda演算(一)大道至简
从选择信息专业开始到回炉读书为止,四舍五入码了八年代码.对于计算机科学的认知仅限于: 1)使用不同语言实现特定功能 2)实现不同算法以增进系统性能 3)搭建不同架构进行组织管理 但从未思考一些本质 ...
- 前端获取Base64字符串格式图片Ajax到后端处理
前端获取到的Base64字符串格式图片一般都是经过处理的图片,例如:裁剪过后的,这里假设data为获取到的Base64字符串格式图片 Base64格式图片的格式为 “data:image/png;ba ...
- 利用dll加载漏洞实现远程代码执行
微软的“不安全dll加载”漏洞涉及Windows XP至Windows 7等多个版本的操作系统.由于Windows存在加载未指明完整路径的dll文件的机制,可能导致用户在使用第三方软件.玩游戏.听音乐 ...
- Codeforces Beta Round #4 (Div. 2 Only) A. Watermelon 水题
A. Watermelon 题目连接: http://www.codeforces.com/contest/4/problem/A Description One hot summer day Pet ...
- 九月回顾 这篇文章和ACM毫无关系= =
其实不只是九月的回顾吧,我大概想把暑假到现在10.01发生的啥事儿都说下吧~ 嗯,我是一个比较沙茶的人,不过运气比较好吧. 高中啊,这个谈起来话就长了,在校什么风采之星大赛上,我认识了个妹子,当时感觉 ...
- mybatis源码分析(2)-----SqlSession创建
1. 在创建好sqlSessionFactory之后,接着就要配置sqlSession的创建. <bean id="simpleTempalte" class="o ...
- TI 28335和AD采集
使用TI 28335和片外AD7606,一个AD有8个通道可以采集,激活AD采集: #define EXTADLZ0 *(int *)0x4200 // Zone 0, ADC data, ADCH1 ...
- 破解NET的四大神器[转]
原本这篇文章可以更早一星期写出来与大家分享,由于某方面的原因耽搁到现在,心里竟有那么一点好像对不住大家的感觉.这当然与神器有关,因为我发现利用这四大神器我似乎觉得几乎所有的NET程序破解都不在话下了 ...
- CDC之CreateCompatibleDC与BitBlt
CreateCompatibleDC 创建一个与指定设备一致的内存设备描写叙述表. HDC CreateCompatibleDC(HDC hdc //设备描写叙述表句柄); 參数 hdc 现有的设备描 ...