zoukankan      html  css  js  c++  java
  • [React] Always useMemo your context value

    Have a similar post about Reac.memo. This blog is the take away from this post.

    To understand why to use 'React.useMemo' or 'React.memo' (basiclly lastest React version use 'useMemo'), is that if the function component or context create a new reference, you need to use memo. 

    Context: 

    Context provider always create a new object to the comsuers. So use memo everytime you can.

    function CountProvider(props) {
      const [count, setCount] = React.useState(0)
      const value = React.useMemo(() => {
        return {
          count,
          setCount,
        }
      }, [count])
      return <CountContext.Provider value={value} {...props} />
    }

    function component:

    Check the props, only do the re-render when props changes.

    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>
      );
    });
  • 相关阅读:
    语言及其文法
    编译原理绪论
    数据库系统绪论
    Flask系列-模板
    进程调度
    Flask系列-程序基本结构
    针对博客园上传md文件有点麻烦的解决方案
    博客样式存档二 (目前样式)
    [省选联考 2020 A 卷] 组合数问题
    退役划水(2)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10829020.html
Copyright © 2011-2022 走看看