[Ts] React.FC는 꼭 써야될까?

장동현·2021년 8월 6일
6

React/TypeScript

목록 보기
2/2
post-thumbnail

React.FC 에 대해서

  • 책에서 React.FC에 대해서 공부하던 중 다른 책에서는 React.FC를 사용하지 않는 것을 발견
  • 이에 대해서 고민을 하기 시작

코드

import React from 'react';
import type {FC} from 'react';
import {Text} from 'react-native';
import * as D from '../data';

export type PersonProps = {
  person: D.IPerson;	
};
// -1-
export default function Person({person}: PersonProps) {
  return <Text>{JSON.stringify(person, null, 2)}</Text>;
}
// -1-
// -2-
export const Person2: FC<PersonProps> = ({person}) => {
  return <Text>{JSON.stringify(person, null, 2)}</Text>;
};
// -2-

코드 설명

  1. function을 사용해서 props 형식으로 가져와서 사용했다.
    • 지금 까지 이렇게 해왔었음
  2. FC(FunctionComponent) 를 사용한 props 설정

이 둘에는 어떤 차이점이 있는가
일단 렌더링 상에서는 차이가 없음

  • Stack overflow를 찾아본 결과 나와 같은 생각을 하는 사람이 많다는 사실을 알게됨

  • 그 내용을 정리해보려고 함


이유 1.

  1. 요즘 찾아보면 함수형으로 작성되는 export function 형이 더 많음

    • Ex : Hook을 이용한 렌더링 관련 코드와 화면 구성 로직 분리



이유 2.

  1. FC 는 항상 children(자식요소)을 포함하게 됨
import React from 'react';
import {SafeAreaView, Text} from 'react-native';
import type {FC} from 'react';

type GreetingProps = {
  name: string;
};

export const Greeting: FC<GreetingProps> = ({name}) => {
  // name is string!
  return <Text>안녕 {name}</Text>;
};
// function Greeting2({name}: GreetingProps) {
//   return <Text>Hello {name}</Text>;
// }
export default function App() {
  return (
    <SafeAreaView>
      <Greeting name="ww8007">
        <Text>"아무것도 안보임"</Text> // -1-
      </Greeting>
    </SafeAreaView>
  );
}

위의 코드에서 Greeting 자체가 children을 이미 포함해서 내보내고 있음

  • 오류가 날 코드인데 기본적으로 오류가 안생김
  • 심지어 children으로 쓴 구문이 보이지가 않음
    - 주석 처리된 Greeting2를 사용하면 <Text> 부분 오류생겨 쓰지도 못함

만약 children 사용하고 싶으면 이렇게 사용

type WithChildren<T = {}> = 
  T & { children?: React.ReactNode };

type CardProps = WithChildren<{
  title: string
}>



이유 3.

  1. defaultProps 사용 불가
  • React.FC를 사용하게 되면 defaultProps를 사용할 수 없다.
  • 물론 defaultProps는 class 기반 지만 사용하고 싶은 경우가 있을 수 있음

[정리]
내가 알고 있던 대로 function을 사용한 component를 생성하는게 더 좋다.
물론 FC를 사용하는게 잘못된 방법도 아니고 맞는 방법임
하지만 children에 대한 명시를 계속해주면서 코드를 작성한다는 점이 좋게 와닿지 않음...

profile
FE 개발자 장동현 입니다 😃

1개의 댓글

comment-user-thumbnail
2022년 7월 30일

import { PropsWithChildren } from 'react'
똑같은 방법으로 리액트에서 지원되는게 있네욤

답글 달기