Skip to content

Instantly share code, notes, and snippets.

@romgrk
Last active May 20, 2021 21:05
Show Gist options
  • Select an option

  • Save romgrk/d0956d19aa6759466813e402cf972c15 to your computer and use it in GitHub Desktop.

Select an option

Save romgrk/d0956d19aa6759466813e402cf972c15 to your computer and use it in GitHub Desktop.
Why I dislike inline styles

Why I dislike inline styles

  1. It mixes behavior, component layout, and style in the same code section, and makes it harder to work on a single of those issues at a time.
  2. It doesn't promote style re-use, which in turn makes the styling less consistent as a whole because there will likely be differences in the inline styles of one file versus the other.
  3. It's less performant. If your component renders 10 times, the engine needs to allocate 10 objects, and then garbage-collect them 10 times. It's hard to understand what causes a GC pause, but short lived objects are the most direct contributor to it. And that is for each style object for each component, which multiplies up fast.

I therefore recommend to at least use the following pattern:

// No
// Objects is recreated at each render :(
function Label({ children }) {
  return (
    <span style={{ fontSize: 10, fontWeight: 'bold', border: '1px solid red' }}>
      {children}
    </span>
  )
}

// Yes
// Constant object, is re-used every time :)
const style = {
  fontSize: 10,
  fontWeight: 'bold',
  border: '1px solid red'
}
function Label({ children }) {
  return <span style={style}>{children}</span>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment