Better, faster, more powerful: styled-components v4

Original author: Evan Jacobs
  • Transfer
The author of the material, the translation of which we publish today, wants to present the beta version of the library styled-components v4 to the web developer community. He, speaking on behalf of the creators of the library, said that now in styled-components there is a new global API for working with styles and native support for properties asand ref. The library .extendchose the path of failure , it is compatible with StrictMode React v16 and has become better, faster and more powerful.



Features styled-components v4


To install the latest version of styled-components, use the following command:

npm install styled-components@beta

You can familiarize yourself with the capabilities of the library, check them out, and if it turns out that something needs to be improved, please inform the developers about it. Here you can find instructions for switching to a new version of the library. Here is the change log for styled-components v4.0.0-beta.0.

Consider the main features of this styled-components release:

  • Reduced size and increased speed. The library size is reduced from 16.1 Kb to less than 15 Kb (its total size depends on your bandler and on the use of the babel plugin). The speed of mounting has increased by about 25%, the speed of re-rendering - by about 7.5%.
  • New API createGlobalStyle, which is a replacement for the old API injectGlobalwith support for hot boot and themes.
  • Support properties as- more flexible alternatives .withComponent().
  • Disposal Comp.extendwith the support of automatic translation of the code base to a unified format styled(Comp).
  • Full compatibility with StrictMode React v16. This also means that developers had to abandon support for React v15 and other older versions of React (although it is possible to use polyfills for organizing work with styled-components v4 in React v15).
  • Native support reffor any styled components, and, thanks to React v16, no need to use innerRef.

The styled-components library was released as a beta version so that those who use it would have enough time for stress testing changes, and so that you can prepare supporting mechanisms like type descriptions and syntax highlighting tools for new API. The library is expected to remain in beta status for about a month.

Performance


When the second version of styled-components was released, we promised, after finalizing the main API, to focus on performance. Since then, thanks to patches, we have increased the performance of the library, which, in particular, led to a 10-fold increase in performance in v3.1.

Work on styled-components speed continues. Due to internal optimizations related to working with memory, due to taking into account the implementation features of the JS engine and code refactoring, the styled-components v4 mount speed for both deep and wide component trees has increased by about 25%. Dynamic style updates have become faster by about 7%. Here is a comparison of the performance of styled-components v3 and v4, based on the results of three tests. The first two relate to the study of mounting component trees, and the third concerns updating components with dynamic styles.


Performance comparison of styled-components v3 and v4

These results, obtained in isolated environments, look impressive. However, it will be quite interesting to compare styled-components v4 with other libraries of the CSS-in-JS ecosystem, in particular, in terms of mount speed.


Performance comparison of styled-components v4 and other libraries

As you can see, the performance of styled-components looks very impressive. In particular, in comparison with the fastest libraries, the styled-components results are within the standard deviation from their results in terms of mount and update speeds. All this allows you to officially declare that performance is no longer a problem with this library.

Although the performance of styled-components is the result of the development of the library and the considerable time and effort spent on improving it, this does not mean that we will no longer deal with performance improvements. If we find an opportunity to make the library even faster, we will use this opportunity.

New global styling API


We have been engaged in the development of a new global styling API for quite a while. The old API,, injectGlobalhas three serious flaws: it does not support dynamic update, hot reboot, and contextual use of themes.

Now we are pleased to present you createGlobalStylea new global styling API that supports dynamic updates. This is how working with it looks like:

import { createGlobalStyle } from"styled-components";
const GlobalStyle = createGlobalStyle`
  html {
    color: red;
  }
`;
exportdefaultfunctionApp() {
  return (
    <div>
      <GlobalStyle />
      This is my app!
    </div>
  );
}

Thanks to their use, createGlobalStyleglobal styles are now part of the React component tree. Although, at first glance, there is nothing special about this, it makes it possible to dynamically update and hot reload styles, and also allows you to use contextual themes for global styles. All this looks exactly the same as when working with any other stylized components.

import { createGlobalStyle, ThemeProvider } from"styled-components";
// Глобальные стили, которые теперь поддерживают обновления и темыconst GlobalStyle = createGlobalStyle`
  html {
    background: ${p => p.backgroundColor}
    color: red;
    font-family: ${p => p.theme.fontFamily};
  }
`;
exportdefaultfunctionApp() {
  return (
    <ThemeProvidertheme={{fontFamily: "HelveticaNeue" }}>
      <GlobalStylebackgroundColor="turquoise" />
    </ThemeProvider>
  );
}

Waiver of .extend and "folding" of components


In this release, styled-components has an internal mechanism, thanks to which the stylized components in wrappers are now automatically “collapsed”, which allows rendering only one component.

What does this mean for library users? The fact is that the API StyledComp.extendappeared in the library in order to allow for some optimizations to be performed, based on the fact that the extensible components were styled components. Due to the internal work on the automatic “folding” of components, styled(StyledComp)the same optimizations that were used thanks to are automatically applied during use StyledComp.extend. This means from.extendNow there is no special benefit, which allowed us to abandon this API. As a result, now library users can write less code and get the opportunity not to waste time on mastering the additional one API. We believe this is very good.

Polymorphic property as


There is another new feature styled-components v4, to which we treat with great enthusiasm. We are talking about the native support of the property asfor any stylized components, which allows you to dynamically influence the rendering during the execution of the program. Consider an example:

import styled from"styled-components"import { Link } from"react-router-dom"// <Component /> рендерит в DOM элемент divconst Component = styled.div`
  color: red;
`
<Component>Hello World!</Component>// Но мы можем сделать так, чтобы он рендерил любой другой HTML-тег или компонент!
<Component as="span">Hello World!</Component>
<Component as={Link} to="home">Hello World!</Component>

If we compare this with the existing mechanism .withComponent(something), the new tool is more flexible, since using it does not need to describe the replacement in advance, and, thanks to the new internal “folding” mechanism, stylization is not lost if the base component is styled-component!

import styled from"styled-components"const RedColor = styled.div`
  color: red;
`const BlueBackgroundRedColor = styled(RedColor)`
  background: blue;
`
<BlueBackgroundRedColor as="span">Hello!</BlueBackgroundRedColor>// Даже хотя мы переключаемся на рендеринг `span` с рендеринга// <RedColor />, объект имеет красный цвет поверх синего // фона!! (.withComponent на это не способен)

As you can see, the property asis just a terrific thing that greatly simplifies the rendering of semantic HTML code anywhere in the application. "Soup" from the tags <div>there is nothing more to justify.

Please note that until we make sure that the property is asable to become a suitable replacement for .withComponentall use cases, we will not discard it. It is assumed that this transition period will not last too long, and we, in the next major release, will remove .withComponent.

React v16 and ref


In the process of transition to the React v16 API, we, among other things, found that, thanks to the new API React.forwardRef, you can get rid of innerRef. We never particularly liked this technique, since it looked like some kind of not very clean hack. But thanks to the excellent work of the React team, you can now use the native ref:

import styled from"styled-components"const Component = styled.div`
  color: red;
`// Позже в функции render
<Component ref={element => { this.myRef = element; }}

Improvements for those writing in TypeScript


We are not doing this directly, but we really like the new @ babel / preset-typescript . Its existence means that now everyone who writes in TypeScript can finally use the babel plugin for styled-components with all its usefulness, including simplified debugging using the names of components in classes, support for server rendering and reducing the size of bundles.

In addition, we completed the translation of TS-types to DefinitelyTyped. Now the community can work with them and correct typing errors at their own pace, without becoming attached to the styled-components releases. Type declarations can be found here .

Results


From this material you learned about the new features of the beta version of the styled-components v4 library and about the improvements made to it. We hope all this is useful to those who use styled-components, and, perhaps, will be interesting to those who are just going to try this library.

Dear readers! Do you use styled-components library in your projects?


Also popular now: