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的更多相关文章

  1. [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 ...

  2. 精读《Function Component 入门》

    1. 引言 如果你在使用 React 16,可以尝试 Function Component 风格,享受更大的灵活性.但在尝试之前,最好先阅读本文,对 Function Component 的思维模式有 ...

  3. [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 ...

  4. [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 ...

  5. 3.React Native在Android中自己定义Component和Module

    React Native终于展示的UI全是Native的UI.将Native的信息封装成React方便的调用. 那么Native是怎样封装成React调用的?Native和React是怎样交互的? V ...

  6. React报错之React Hook 'useEffect' is called in function

    正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...

  7. [React & Debug] Quick way to debug Stateless component

    For example we have the following code: const TodoList = (props) => ( <div className="Tod ...

  8. react 使用react-router-dom 在Route对象上component 参数接收的是一个方法而非一个对象

    其实对于jsx语法 一直觉的它有点清晰都不是很好,js和html混在一起有点不伦不类的样子,以下是我在使用react中遇到的一个很奇葩的事情 假定你定义了一个component Mine import ...

  9. 《React Native 精解与实战》书籍连载「React Native 底层原理」

    此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...

随机推荐

  1. HTML框架与表单

    1.框架处理结构 <html> <head> <meta http-equiv="Content-Type" content="text/h ...

  2. 备份Kylin的Metadata

    元数据是Kylin中最重要的数据之一,备份元数据时运维工作中一个至关重要的环节.只有这样,在由于误操作导致整个Kylin服务或某个Cube异常时,才能将Kylin快速从备份中恢复出来. Kylin组织 ...

  3. hdu 4819 二维线段树模板

    /* HDU 4819 Mosaic 题意:查询某个矩形内的最大最小值, 修改矩形内某点的值为该矩形(Mi+MA)/2; 二维线段树模板: 区间最值,单点更新. */ #include<bits ...

  4. [BZOJ5010][FJOI2017]矩阵填数(状压DP)

    5010: [Fjoi2017]矩阵填数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 90  Solved: 45[Submit][Status][ ...

  5. [NC13C]形态形成场/[Gym100430B]Divisible Substrings

    [NC13C]形态形成场/[Gym100430B]Divisible Substrings 题目大意: 有\(m(m\le26)\)个字符串替换式\(S_i(|S_i\le100|)\),表示某个大写 ...

  6. [CodeForces-708E]Student's Camp

    题目大意: 一个n*m的墙,被吹k天风,每块靠边的砖都有p的概率被吹掉. 如果上下两行没有直接相连的地方,我们则认为这一堵墙已经倒塌. 问最后墙不倒塌的概率(模意义). 思路: 动态规划. 用f[i] ...

  7. Educational Codeforces Round 12 C. Simple Strings 贪心

    C. Simple Strings 题目连接: http://www.codeforces.com/contest/665/problem/C Description zscoder loves si ...

  8. HDU 5651 xiaoxin juju needs help 数学

    xiaoxin juju needs help 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5651 Description As we all k ...

  9. Codeforces Round #302 (Div. 2) C. Writing Code 简单dp

    C. Writing Code Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/544/prob ...

  10. 拉普拉斯(Laplace)分布

    Laplace分布的概率密度函数的形式是这样的: $p(x) = \frac{1}{2 \lambda} e^{-\frac{\vert x –\mu \vert}{\lambda}}$   一般$\ ...