본문으로 건너뛰기
Previous
Next
Emotion 완벽 가이드 | CSS-in-JS·성능·Styled·CSS Prop·실전 활용

Emotion 완벽 가이드 | CSS-in-JS·성능·Styled·CSS Prop·실전 활용

Emotion 완벽 가이드 | CSS-in-JS·성능·Styled·CSS Prop·실전 활용

이 글의 핵심

Emotion으로 고성능 CSS-in-JS를 구현하는 완벽 가이드. Styled, CSS Prop, Theming, SSR, TypeScript까지 실전 예제로 정리. Emotion·CSS-in-JS·React 중심으로 설명합니다.

이 글의 핵심

Emotion으로 고성능 CSS-in-JS를 구현하는 완벽 가이드입니다. Styled, CSS Prop, Theming, SSR, TypeScript까지 실전 예제로 정리했습니다.

실무 경험 공유: styled-components에서 Emotion으로 전환하면서, 번들 크기가 20% 감소하고 성능이 향상된 경험을 공유합니다.

들어가며: “CSS-in-JS가 느려요”

실무 문제 시나리오

시나리오 1: styled-components가 느려요

런타임 오버헤드가 있습니다. Emotion은 더 빠릅니다. 시나리오 2: 번들 크기가 커요

styled-components는 14KB입니다. Emotion은 7KB입니다. 시나리오 3: 더 유연한 API가 필요해요

styled만으로는 제한적입니다. Emotion은 css prop도 제공합니다.

1. Emotion이란?

핵심 특징

Emotion은 고성능 CSS-in-JS 라이브러리입니다. 주요 장점:

  • 빠름: 최적화된 성능
  • 작은 크기: 7KB
  • 유연함: Styled + CSS Prop
  • TypeScript: 완벽한 지원
  • SSR: 서버 사이드 렌더링

2. 설치 및 기본 사용

설치

npm install @emotion/react @emotion/styled

Styled API

import styled from '@emotion/styled';
const Button = styled.button`
  background: #3498db;
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  &:hover {
    opacity: 0.8;
  }
`;
export default function App() {
  return <Button>Click me</Button>;
}

3. CSS Prop

설정 (Vite)

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
  plugins: [
    react({
      jsxImportSource: '@emotion/react',
    }),
  ],
});

사용

/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const buttonStyle = css`
  background: #3498db;
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  &:hover {
    opacity: 0.8;
  }
`;
export default function App() {
  return <button css={buttonStyle}>Click me</button>;
}

4. Props 기반 스타일

import styled from '@emotion/styled';
interface ButtonProps {
  variant?: 'primary' | 'secondary';
  size?: 'small' | 'large';
}
const Button = styled.button<ButtonProps>`
  background: ${(props) => (props.variant === 'primary' ? '#3498db' : '#2ecc71')};
  color: white;
  padding: ${(props) => (props.size === 'small' ? '0.25rem 0.5rem' : '0.5rem 1rem')};
  border: none;
  border-radius: 4px;
  cursor: pointer;
`;
// 사용
<Button variant="primary" size="small">Small Primary</Button>

5. Theming

import { ThemeProvider } from '@emotion/react';
const theme = {
  colors: {
    primary: '#3498db',
    secondary: '#2ecc71',
    text: '#333',
    background: '#fff',
  },
  spacing: {
    sm: '0.5rem',
    md: '1rem',
    lg: '2rem',
  },
};
const Button = styled.button`
  background: ${(props) => props.theme.colors.primary};
  color: white;
  padding: ${(props) => props.theme.spacing.md};
`;
export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <Button>Themed Button</Button>
    </ThemeProvider>
  );
}

6. TypeScript 타입

import '@emotion/react';
declare module '@emotion/react' {
  export interface Theme {
    colors: {
      primary: string;
      secondary: string;
      text: string;
      background: string;
    };
    spacing: {
      sm: string;
      md: string;
      lg: string;
    };
  }
}

7. Global Styles

import { Global, css } from '@emotion/react';
const globalStyles = css`
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
  }
`;
export default function App() {
  return (
    <>
      <Global styles={globalStyles} />
      {/* 나머지 컴포넌트 */}
    </>
  );
}

8. Composition

import { css } from '@emotion/react';
const baseStyle = css`
  padding: 0.5rem 1rem;
  border-radius: 4px;
`;
const primaryStyle = css`
  ${baseStyle}
  background: #3498db;
  color: white;
`;
const secondaryStyle = css`
  ${baseStyle}
  background: #2ecc71;
  color: white;
`;
// 사용
<button css={primaryStyle}>Primary</button>
<button css={secondaryStyle}>Secondary</button>

9. SSR (Next.js)

_document.tsx

import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document';
import { CacheProvider } from '@emotion/react';
import createEmotionServer from '@emotion/server/create-instance';
import createCache from '@emotion/cache';
function createEmotionCache() {
  return createCache({ key: 'css' });
}
export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const originalRenderPage = ctx.renderPage;
    const cache = createEmotionCache();
    const { extractCriticalToChunks } = createEmotionServer(cache);
    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App: any) => (props) => (
          <CacheProvider value={cache}>
            <App {...props} />
          </CacheProvider>
        ),
      });
    const initialProps = await Document.getInitialProps(ctx);
    const emotionStyles = extractCriticalToChunks(initialProps.html);
    const emotionStyleTags = emotionStyles.styles.map((style) => (
      <style
        data-emotion={`${style.key} ${style.ids.join(' ')}`}
        key={style.key}
        dangerouslySetInnerHTML={{ __html: style.css }}
      />
    ));
    return {
      ...initialProps,
      styles: [...React.Children.toArray(initialProps.styles), ...emotionStyleTags],
    };
  }
  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

10. 실전 예제: 버튼 시스템

import styled from '@emotion/styled';
import { css } from '@emotion/react';
interface ButtonProps {
  variant?: 'primary' | 'secondary' | 'danger';
  size?: 'small' | 'medium' | 'large';
  fullWidth?: boolean;
}
const Button = styled.button<ButtonProps>`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
  ${(props) => {
    const variants = {
      primary: css`
        background: #3498db;
        color: white;
        &:hover {
          background: #2980b9;
        }
      `,
      secondary: css`
        background: #2ecc71;
        color: white;
        &:hover {
          background: #27ae60;
        }
      `,
      danger: css`
        background: #e74c3c;
        color: white;
        &:hover {
          background: #c0392b;
        }
      `,
    };
    return variants[props.variant || 'primary'];
  }}
  ${(props) => {
    const sizes = {
      small: css`
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
      `,
      medium: css`
        padding: 0.5rem 1rem;
        font-size: 1rem;
      `,
      large: css`
        padding: 0.75rem 1.5rem;
        font-size: 1.125rem;
      `,
    };
    return sizes[props.size || 'medium'];
  }}
  ${(props) =>
    props.fullWidth &&
    css`
      width: 100%;
    `}
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;
// 사용
<Button variant="primary" size="small">Small Primary</Button>
<Button variant="secondary">Medium Secondary</Button>
<Button variant="danger" size="large" fullWidth>Large Danger Full Width</Button>

정리 및 체크리스트

핵심 요약

  • Emotion: 고성능 CSS-in-JS
  • Styled + CSS Prop: 유연한 API
  • 빠름: 최적화된 성능
  • 작은 크기: 7KB
  • TypeScript: 완벽한 지원
  • SSR: 서버 사이드 렌더링

구현 체크리스트

  • Emotion 설치
  • Styled API 사용
  • CSS Prop 활용
  • Props 기반 스타일
  • Theming 구현
  • Global Styles
  • SSR 설정
  • TypeScript 타입

같이 보면 좋은 글


이 글에서 다루는 키워드

Emotion, CSS-in-JS, React, Performance, Theming, TypeScript, Frontend

내부 동작과 핵심 메커니즘

이 글의 주제는 「Emotion 완벽 가이드 | CSS-in-JS·성능·Styled·CSS Prop·실전 활용」입니다. 앞선 튜토리얼을 구현·런타임 관점에서 다시 압축합니다. 구성 요소 간 책임 분리와 관측 가능한 지점을 기준으로 “입력이 어디서 검증되고, 핵심 연산이 어디서 일어나며, 부작용(I/O·네트워크·디스크)·동시성이 어디서 터지는가”를 한 장면으로 그리면 장애 분석이 빨라집니다.

처리 파이프라인(개념도)

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]

경계에서의 지연·실패(시퀀스 관점)

sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(프로세스·런타임·게이트웨이)
  participant D as 의존성(외부 API·DB·큐)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)

알고리즘·프로토콜·리소스 관점 체크포인트

  • 불변 조건(Invariant): 각 단계가 만족해야 하는 조건(버퍼 경계, 프로토콜 상태, 트랜잭션 격리, 파일 디스크립터 상한)을 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 동일 입력에 동일 출력이 보장되는 순수 층과, 시간·네트워크·스레드 스케줄에 의해 달라질 수 있는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화/역직렬화, 문자 인코딩, syscall 횟수, 락 경합, GC·할당, 캐시 미스처럼 누적 비용을 의심 목록에 넣습니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때(소켓 버퍼, 큐 깊이, 스트림) 어디서 어떤 신호로 속도를 줄일지 정의합니다.

프로덕션 운영 패턴

실서비스에서는 기능과 함께 관측·배포·보안·비용·규제가 동시에 요구됩니다.

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율/지연 분위수(p95/p99), 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시 계층·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션 호환성·플래그가 문서화되어 있는가
용량피크 트래픽·디스크·파일 디스크립터·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 가능한 한 프로덕션에 가깝게 맞추는 것이 재현율을 높입니다.


확장 예시: 엔드투엔드 미니 시나리오

「Emotion 완벽 가이드 | CSS-in-JS·성능·Styled·CSS Prop·실전 활용」을 실제 배포·운영 흐름으로 옮긴 체크리스트형 시나리오입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드 표를 API 또는 이벤트 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 한 화면(로그+메트릭+트레이스)에서 추적한다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지(또는 피처 플래그) 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값이 기대 범위인지 본다.

의사코드 스케치(프레임워크 무관)

handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)        // 경계에서 거절
  authorize(validated, ctx)                  // 권한·테넌트
  result = domainCore(validated)             // 순수에 가까운 규칙
  persistOrEmit(result, idempotentKey)       // I/O: 멱등·재시도 정책
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성 불안정, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정이 로컬과 다름프로필·시크릿·기본값, 지역 리전단일 소스(예: 스키마 검증된 설정)와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

자주 묻는 질문 (FAQ)

Q. styled-components와 비교하면 어떤가요?

A. Emotion이 더 빠르고 번들 크기가 작습니다. API는 거의 동일합니다.

Q. CSS Prop이 뭔가요?

A. JSX에서 직접 css를 작성할 수 있는 기능입니다.

Q. MUI와 함께 사용할 수 있나요?

A. 네, MUI는 Emotion을 기본으로 사용합니다.

Q. 프로덕션에서 사용해도 되나요?

A. 네, MUI, Chakra UI 등이 Emotion을 사용하고 있습니다.