React.FC

유의진·2024년 12월 3일
0
post-thumbnail

FC란

Function Component 타입의 줄임말이다.

React.FC

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

type FC<P = {}> = FunctionComponent<P>;
  • PropsWithChildren<P>를 사용하여 children props를 포함한다.
  • defaultProps, propTypes, displayName의 prop로 포함

장점

  • props의 타입을 간단하게 정의 가능하다.
  • defaultProps, propTypes, displayName 등의 정적 속성을 쉽게 사용 가능하다.

단점

  • children이 항상 포함된다.
  • 컴포넌트의 타입 선언이 더 불명확해질 수 있다.

가장 큰 단점

React.FC를 사용할 경우 props에 자동으로 children이 옵셔널로 들어가있다.

→ 단점인 이유는 children의 명확하지 않은 타입 지정이기 때문이다.

→ 모든 컴포넌트를 React.FC로 선언했을 때 children이 필요하지 않은 컴포넌트에도 명시를 해놓지 않았기 때문에 children을 사용할 수 있는 문제가 발생한다.

컴포넌트 변경

현재 만들어둔 Chip 컴포넌트는 이렇게 구성되어 있다.

export const Chip: React.FC<ChipProps> = ({
  className,
  variant = 'default',
  size = 'sm',
  children,
  ...props
}) => {
  const chipClass = cn(
    chipStyles.base,
    chipStyles.variant[variant],
    chipStyles.size[size],
    className,
  );

  return (
    <button className={chipClass} {...props}>
      <div className="size-18 rounded-6 border border-slate-200 bg-white">
        {variant === 'active' && <FaCheck className="size-16 text-blue-600" />}
      </div>
      {children}
    </button>
  );
};

이러한 방식으로 바꿔야 children에 대한 명확한 타입 지정이 가능하다.

export const Chip = ({
  className,
  variant = 'default',
  size = 'sm',
  children,
  ...props
}: ChipProps) => {
  const chipClass = cn(
    chipStyles.base,
    chipStyles.variant[variant],
    chipStyles.size[size],
    className,
  );

  return (
    <button className={chipClass} {...props}>
      <div className="size-18 rounded-6 border border-slate-200 bg-white">
        {variant === 'active' && <FaCheck className="size-16 text-blue-600" />}
      </div>
      {children}
    </button>
  );
};

참고

React.FC 정의
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts

profile
안녕하세요. 프론트엔드 개발 공부를 하고 있습니다.

0개의 댓글

관련 채용 정보