[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把对象作为程序的基本单元,一个对象包含了数据和操作数据的 ...
- Knockout.js(四):自定义绑定
除了内嵌的绑定,还可以创建一些自定义绑定,封装复杂的逻辑或行为. 注册绑定 添加子属性到ko.bindingHandlers来注册绑定: ko.bindingHandlers.yourBindingN ...
- Redis_NoSql分布式数据库CAP原理
前文简单介绍了NoSql数据库的四大分类以及常用的数据库技术,本文简单介绍分布式数据库CAP原理. 一.传统的CAID是什么 1. A(Atomicity)原子性:事务里的所有操作要么全部做完,要么都 ...
- JDK源码(1.7) -- java.util.AbstractList<E>
java.util.AbstractList<E> 源码分析(JDK1.7) ------------------------------------------------------- ...
- python开发_gzip_压缩|解压缩gz文件_完整版_博主推荐
''' gzip -- 支持gzip文件 源文件:Lib/gzip.py 这个模块提供了一些简单的接口来对文件进行压缩和解压缩,类似于GNU项目的gzip和gunzip. 数据的压缩源于zlib模块的 ...
- .apk文件的MIME类型
IIS7中下载apk文件会报404错误. 找到:IIS目录,MIME类型 添加.apk文件的MIME类型. 文件扩展名:.apk MIME类型:application/vnd.android.pack ...
- Android ButterKnife注解框架使用
这段时间学习了下ButterKnife注解框架,学习的不是特别深入,但是基础也差不多了,在此记录总结一下. ButterKnife是一个Android View注入的库,主要是注解的使用,可以减少很多 ...
- axios 与 Jquery-ajax 的使用区别
axios 和 ajax 的使用方法基本一样,只有个别参数不同: 附:axios 中文文档 一.axios axios({ url: 'http://jsonplaceholder.typicode. ...
- 设计模式 - 观察者模式(Observer Pattern) Java内置 用法
观察者模式(Observer Pattern) Java内置 用法 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26601659 ...
- systemd-udevd
描述:systemd-udevd是监听内核发出的设备事件,并根据udev规则处理每个事件. 选项: --daemon 脱离控制台,并作为后台守程运行. --debug 在标准错误上打印调试信息 --c ...