简体   繁体   English

ThemeProvider 的 useMemo 与 useEffect

[英]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

  • It is primarily there for handling async logic as a pattern它主要用于将异步逻辑作为模式处理
  • It is not executed during Server-Side Rendering在服务器端渲染期间不执行
  • It runs after the DOM is rendered (users will briefly see the wrong styles)它在 DOM 渲染后运行(用户会短暂地看到错误的样式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM