How styled-components works: A deep dive under the hood

Original icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY

Magic Syntax

Let’s create a simple button with static styles using styled-components:

Reinvent styled-components

styled-components Under The Hood

Import styled-components

When you import the library first time in you app it creates an internal counter variable to count all the components created via the styled factory.

call styled.tag-name factory

componentWillMount()

Lets create instance of the above Button and mount it into the page:

render()

As it’s finished with CSS now styled-components just needs to create an element with corresponding className:

  1. this.props.className — optional passed by parent component.
  2. componentId — uniq identifier of a component but not component instance. This class has no any CSS rules but it is used in nesting selectors when need to refer to other component.
  3. generatedClassName — uniq per every component instance which has actual CSS rules.

componentWillReceiveProps()

Now let’s try to change our button props when it is mounted. To do this we need to make more interactive example for our Button:

  1. Evaluate the tagged template.
  2. Generate the new CSS class name.
  3. Preprocess the styles with stylis.
  4. Inject the preprocessed CSS into the page.

Performance tips

Knowing how styled-components works under the hood we can focus on performance better.

Over 200 classes were generated for component styled.button. 
Consider using the attrs method, together with a style object for frequently changed styles.
Example:
const Component = styled.div.attrs({
style: ({ background }) => ({
background,
}),
})`width: 100%;`
<Component />

Conclusion

styled-components workflow is pretty straightforward, it creates necessary CSS on the fly right before components render and it is fast enough despite evaluating tagged strings and preprocessing CSS right in the browser.

--

--

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store