zoukankan      html  css  js  c++  java
  • [React] Optimize context value

    The way that context works is that whenever the provided value changes from one render to another, it triggers a re-render of all the consuming components (which will re-render whether or not they’re memoized).

    So take this for example:

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

    Every time the <CountProvider /> is re-rendered, the value is brand new, so even though the count value itself may stay the same, all component consumers will be re-rendered.

    This can be problematic in certain scenarios. You can read more about this here.

    The quick and easy solution to this problem is to memoize the value that you provide to the context provider:

    const CountContext = React.createContext()
    
    function CountProvider(props) {
      const [count, setCount] = React.useState(0)
      const value = React.useMemo(() => [count, setCount], [count])
      return <CountContext.Provider value={value} {...props} />
    }
  • 相关阅读:
    Java 标识符
    Java 关键字详解
    Java 语言的主要特性
    redis学习
    垃圾回收
    JVM内存结构
    sql总结(DML)
    sql总结(DDL)
    加密算法
    《数据结构》 定长顺序串常用操作代码集合
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13861843.html
Copyright © 2011-2022 走看看