Emotion: Component-Scoped Styles in JavaScript
Emotion lets you write CSS directly in your JavaScript, keeping styles and logic colocated. It's ideal for dynamic, component-scoped styles in React that avoid global conflicts.
WHY IT EXISTS Traditional CSS lives in global files, leading to naming collisions, dead code, and difficulty managing styles tied to a component's state. CSS-in-JS libraries like Emotion were created to scope styles directly to components and leverage JavaScript's power for dynamic styling.
THE MENTAL MODEL Think of Emotion as bringing your CSS stylesheet directly into your component file. Instead of referencing an external class name like className="primary-button", you define the styles for that button right where you use it, using JavaScript variables, functions, and props to make them dynamic.
HOW IT WORKS Emotion parses your JavaScript-written CSS (either as template literals or objects) at runtime or build time. It generates unique, scoped class names (e.g., css-1q2w3e4) and injects the corresponding CSS rules into the document's <head>. This ensures styles don't leak and only the CSS for rendered components is loaded. It supports two main patterns: the css prop for applying styles directly to an element, and the styled factory for creating reusable styled components (e.g., styled.button).
WHEN TO USE IT Use Emotion in component-based applications (especially React) where you need dynamic styling based on component state or props. It's excellent for building design systems with theming, as components can easily consume theme values. It also simplifies server-side rendering (SSR) of styles, often with zero configuration in modern React frameworks.
WHEN NOT TO USE IT For static sites with simple, non-dynamic styling, Emotion can be overkill; traditional CSS or a utility-first framework might be simpler and have less runtime overhead. If your team is not comfortable with JavaScript or prefers a strict separation of concerns between JS, HTML, and CSS, it might not be a good cultural fit.
ONE CANONICAL EXAMPLE A common use case is creating a themed button component. Using the styled API, you can define a component that accepts a primary prop. If the prop is true, it pulls a color from a theme object; otherwise, it uses a default. For example: const Button = styled.button(props => ({ backgroundColor: props.primary ? props.theme.colors.primary : 'grey' }));. This creates a <Button primary /> component that is self-contained and reusable across an application.
Read the original → emotion.sh
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.