首页 > 其他 > 详细

[React] Optimize context value

时间:2020-10-23 09:38:21      阅读:22      评论:0      收藏:0      [点我收藏+]

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} />
}

 

[React] Optimize context value

原文:https://www.cnblogs.com/Answer1215/p/13861843.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!