What is the actual difference between using an inline-style and using a css-in-js library like styled components in React?

Viewed 3573

Writing an inline style in js,

const styles = {
    background: 'blue',
    color: 'white'
}

and using it in the JSX as below

<div style={styles}> I am a div </div>

Writing the styles using 'styled components',

const Div= styled.div`
     background: 'blue',
     color: 'white'
`

and using it like,

<Div> I am a Div </Div>

Here what is the difference in using a css-in-js library and using the inline styles.

1 Answers

First, your styled.div example is wrong, as in CSS-in-JS you write actual CSS and not an Object-like style:

// "Real CSS"
const Div= styled.div`
  background: blue;
  color: white;
`

Second, CSS classes are generally better, also, inline styles are considered bad practice as it is hard to re-use and maintain styles.

CSS classes are generally better for performance than inline styles.

So in conclusion:

  1. In inline styles, you write Object-like styles vs. actual CSS
  2. Writing CSS allows all the benefits of CSS (like selectors).
  3. Re-use and maintaining CSS is much easier than inline styles.
  4. The real debate is between CSS-in-JS vs. CSS modules vs. SASS vs. Normal CSS (for that you can google or read related questions in SO).
  5. Inline styles considered bad-practice as in addition they override all defined styles.
  6. Inline-styles are limited in their functionality (try animating something in inline style or even implementing a media query).
Related