[英]useMemo vs useEffect for ThemeProvider
I created ThemeProvider component where it retrieves the design tokens from json which is passed in as tokens
prop, then it inserts those tokens into style attribute of parent div.我创建了 ThemeProvider 组件,它从 json 中检索设计令牌,作为
tokens
道具传入,然后将这些令牌插入到父 div 的样式属性中。 And ThemeProvider wraps the children component so children can use those styles. Since consumers won't be updating tokens often, I just need to run the retrieveToken function once in the initial render. ThemeProvider 包装了子组件,以便孩子可以使用那些 styles。由于消费者不会经常更新令牌,我只需要在初始渲染中运行一次 retrieveToken function。 My question is should I use useEffect with empty dependency or should I be using useMemo to cache the result of retrieveToken function?
我的问题是我应该使用具有空依赖项的 useEffect 还是应该使用 useMemo 来缓存 retrieveToken function 的结果? My guess is useEffect with empty dependency is enough since token prop won't be updated at all, only needed for initial run.
我的猜测是具有空依赖项的 useEffect 就足够了,因为 token prop 根本不会更新,只需要在初始运行时使用。
const [tokenObj, setTokenObj] = useState({});
const {tokens} = props;
function retrieveToken(tokens){
// expensive operation, but only needed to run once in initial render
}
//which way is better?
// Option1 - react useMemo
const tokenObj2 = React.useMemo(() => {
return retrieveToken(tokens);
},[tokens]);
//Option2 - react useEffect
React.useEffect(() => {
setTokenObj(retrieveToken(tokens))
},[])
return (
<div style={tokenObj}> {children} </div>
)
useMemo
is the right one to use and is purpose made for running expensive synchronous operations less often. useMemo
是正确的使用方式,旨在减少运行昂贵的同步操作的频率。
useEffect
should not be used for a few reasons:出于以下几个原因,不应使用
useEffect
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.