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>
      );
    });
  • 相关阅读:
    java的概述 常量 变量
    css 基础2
    css 盒子模型1
    css 基础1
    HTML 基础 3
    HTML基础2
    servletContext百科
    hibernate 一对多双向关联 详解
    hibernate generator class="" id详解
    Hibernate缓存原理与策略
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10829020.html
Copyright © 2011-2022 走看看