📜 ⬆️ ⬇️

Better, faster, more powerful: styled-components v4

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. Speaking on behalf of the creators of the library, he says that now in styled-components there is a new global API for working with styles and native support for the as and ref properties. The library followed the path of abandoning .extend , 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 library's capabilities, check them out, and if it turns out that something needs to be improved in it, 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:


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, by mount speed.


Performance comparison of styled-components v4 and other libraries

As you can see, the performance of the 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, injectGlobal , has three major flaws: it does not support dynamic update, hot reboot, and contextual use of themes.

Now we are pleased to introduce createGlobalStyle , a 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; } `; export default function App() { return (   <div>     <GlobalStyle />     This is my app!   </div> ); } 

Using createGlobalStyle global 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}; } `; export default function App() { return (   <ThemeProvider theme={{ fontFamily: "Helvetica Neue" }}>     <GlobalStyle backgroundColor="turquoise" />   </ThemeProvider> ); } 

Waiver of .extend and "folding" of components


In this release, the styled-components have 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 point is that the StyledComp.extend API appeared 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, when using styled(StyledComp) the same optimizations that were used thanks to StyledComp.extend are automatically applied. This means that there is no special benefit from .extend , which made it possible 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 as property for any stylized components, which allows us to dynamically influence rendering during the execution of the program. Consider an example:

 import styled from "styled-components" import { Link } from "react-router-dom" // <Component />   DOM  div const 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 .withComponent(something) mechanism, then 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. 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 as property is simply a terrific piece that greatly simplifies the rendering of semantic HTML code anywhere in the application. “Soup” from <div> tags has nothing more to justify.

Please note that until we make sure that the as property is capable of becoming a suitable replacement for .withComponent in all use cases, we will not reject it. It is assumed that this transitional period will not last too long, and we will remove .withComponent in the next major release.

React v16 and ref


During the transition to the React v16 API, we also found that, thanks to the new React.forwardRef API, you can get rid of the 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?

Source: https://habr.com/ru/post/422783/


All Articles