5

CSS-in-JS 性能成本缓解策略

 4 years ago
source link: https://www.infoq.cn/article/Ie1CU2rJdXh7HjlexeeJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作为一种将组件逻辑链接到其样式的方式,CSS-in-JS 在某些场景中变得流行起来。 Aggelos Arvanitakis 提醒开发人员 ,在某些情况下,不再能忽略 CSS-in-JS 的成本,并且提供了缓解策略。

Arvanitakis 在一篇文章中指出,尽管 CSS-in-JS 带来了 好处 ,但是,它仍可能在某些应用程序中造成性能问题。Arvanitakis 把重点放在React 和两个流行的CSS-in-JS 库( styled-componentsemotion )上,他比较了相同代码的两个版本,其中只有一个版本使用了 CSS-in-JS 样式。无样式版本如下所示:

复制代码

importReactfrom'react';
constNormalDiv =props=><div{...props} />
const App = () => {
const [randomValue, setRandomValue] = React.useState(0);
return (
<React.Fragment>
{new Array(50).fill(null).map((__, i) => (
<NormalDivkey={i}>Hello World</NormalDiv>
))}
<buttononClick={()=>setRandomValue(Math.random())}>Force Rerender</button>
</React.Fragment>
);
};

样式版本如下所示:

复制代码

importstyledfrom'@emotion/styled';
constStyledDiv = styled.div``;
constApp =()=>{
const[randomValue, setRandomValue] = React.useState(0);
return(
<React.Fragment>
{new Array(50).fill(null).map((__, i) => (
<StyledDivkey={i}>Hello World</StyledDiv>
))}
<buttononClick={()=>setRandomValue(Math.random())}>Force Rerender</button>
</React.Fragment>
);
};

样式化的 CSS-in-JS 的实现比无样式版本要多花 50% 的时间在渲染上。尽管在很多情况下,很难察觉与 CSS-in-JS 相关的性能成本,但在其他情况下(如具有大型组件树),它的成本是很难忽略的。Arvantitakis 猜测使用某些库观察到的性能成本可能要归因于它们修改组件树(使用 Context 并添加 Context.Consumer 以读取样式值)以及动态地应用样式(


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK