[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 组件布局.组件与 ...
随机推荐
- Python 面向对象编程——初见
<什么是面向对象> 面向对象编程(Object Oriented Programming),简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的 ...
- hiho1393二分图多重匹配
题目链接:[http://hihocoder.com/problemset/problem/1393] 题意:中文题意. 题解:二分图的多重匹配.主要是建图然后跑一个最带流,再判断一下就可以了. 建图 ...
- BZOJ2938 POI2000病毒
我们不能让重复过的字串出现在无限串上(就叫这个了...) 也就是要自动机一直能匹配但就是匹配不到,那么就是在自动机上找一个环. dfs判环即可.注意是个有向图. #include<bits/st ...
- [BZOJ5427]最长上升子序列
考虑O(n log n)的LIS求法,dp[i]表示到目前为止,长度为i的LIS的末尾最小是多少. 当当前数确定时直接用LIS的求法更新dp数组,当不确定时,由于这个数可以是任意数,所以可以接在任意上 ...
- ssm整合总结(一)--第一步之使用maven搭建一个web项目
本文内容来自:山硅谷,本文内容整合了任务2,任务3,任务4内容.http://www.gulixueyuan.com/my/course/50 1说明 1.1该项目使用的知识点有 1.1.1校验方式是 ...
- SpringBoot 部署 docker 打包镜像
SpringBoot 部署 docker 打包镜像 环境: 1.代码编写工具:IDEA 2.打包:maven 3.docker 4.linux 7.JDK1.8 8.Xshell 9.Xftp 第一步 ...
- JavaScript学习笔记 isPrototypeOf和hasOwnProperty使用区别
1.isPrototypeOf isPrototypeOf是用来判断指定对象object1是否存在于另一个对象object2的原型链中,是则返回true,否则返回false. 格式如下: object ...
- python开发_tkinter
Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用, 同样可以应用在Windows和Macint ...
- layoutit note
Head: JavaScript -> Navbar Menu: JavaScript -> Collapse Compnents -> Panels Compnents -> ...
- jQuery使用一知半解
jQuery是目前使用最广泛的javascript函数库.据统计,全世界排名前100万的网站,有46%使用jQuery,远远超过其他库.微软公司甚至把jQuery作为他们的官方库.对于网页开发者来说, ...