Skip to content

[기술 공유] Reactjs 컴포넌트 선언 방식을 화살표 함수로 할지 함수 선언문으로 할지

Coa edited this page Mar 9, 2022 · 2 revisions

최상위 함수 _app에서는 function 키워드를 사용했는데 나머지는 const로 해야 하는 이유?

image

저는 함수 선언 타이핑을 위한 타이프스크립트에서 일급 지원을 받고자 하는 당신의 열망을 전적으로 공유합니다.

스타일과 일관성이 있는 이점뿐만 아니라

현재로서는 단순히 함수 호이스팅의 장점을 얻을 수 없습니다.

또한 기존 유형을 사용하여 함수의 타입을 선언합니다.

React with TypeScript: Components as Function Declarations vs. Function Expressions

https://github.com/Microsoft/TypeScript/issues/22063

When I first started learning TypeScript and using it with React, I followed patterns. A friend showed me how to type a component. I used that as an example whenever I created a new component. This example looked something like this:

const MyComponent: React.FC = () => <h1>Hello, world!</h1>

Experimenting with this pattern, I thought to myself, “If I want to declare a component using the function keyword, then I bet I can do the same thing.”

function MyComponent(): React.FC {
  return <h1>Hello, world!</h1>
}

Sadly, this is not valid. Instead of investigating deeper, I decided to stick with what worked (using function expressions like the first example).

Eight months later, after diving deeper into TypeScript, I’ve finally learned the difference and understand why my first attempt didn’t work.

Typing a React Component as a Function Expression

함수 표현식으로 React 컴포넌트를 입력할 때(예: i.e. const MyComponent: React.FC<Props>)는 다음과 같은 질문을 던져야 합니다. "이 변수 MyComponent는 what type of value를 가지고 있습니까?"

function type에 주석을 다는 이유는 이 변수가 function를 가지고 있기 때문입니다. React.FC는 "React Function Component"를 나타냅니다.

Typing a React Component as a Function Declaration

In the other instance, when we type a React component as a function declaration (i.e. function MyComponent), we ask the same thing.

다른 예에서는 함수 선언(i.e. function MyComponent)으로 리액트 컴포넌트를 입력할 때 동일한 것을 묻습니다.

이번에는 function return type에 주석을 달겠습니다. 그래서 같은 타입을 사용할 수 없는 거군요!

대신 TypeScript에 "이봐! 이 기능은 React 컴포넌트를 반환합니다." 그래서 그게 어떻게 보여? 다음과 같습니다.

function MyComponent(): React.ReactNode {
  return <h1>Hello, world!</h1>
}

이제 TypeScript는 이 함수가 특정 유형의 리액트노드를 반환한다는 것을 알고 있습니다. 이전에 ReactNode를 보지 못한 경우 @type/react 선언 파일에서 다음과 같은 유니온 유형임을 알 수 있습니다.

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

이것들은 부품에서 반품할 수 있는 모든 유효한 것들입니다. 여기서 소스 코드를 자유롭게 살펴보십시오.

이제 함수 표현식과 함수 선언으로 React 구성요소를 올바르게 입력하는 방법을 알게 되었습니다! 자세한 내용은 react-typecript-cheatsheet를 참조하십시오.

Typing Props with a Function Expression

구성요소가 props를 사용할 때는 props가 어디에 추가되는지도 알아야 합니다. 예는 다음과 같습니다

type Props = {
  name: string;
}
const MyComponent: React.FC<Props> = ({ name}) => <h1>Hello, {name}!</h1>

또한 PropsWithChildren이라는 편리한 유형을 사용할 수 있으며 자동으로 children이 포함됩니다.

type Props = {
  name: string;
}

const MyComponent: React.FC<**PropsWithChildren<Props>**> 
	= ({ name, children }) 
	=> <h1>{children}, {name}!</h1>

Typing Props with a Function Declaration

함수 선언에서도 같은 일을 할 수 있다.

type Props = {
  name: string;
}function MyComponent({ name }: Props): React.ReactNode {
  return <h1>Hello, {name}!</h1>
}

And the same for using PropsWithChildren :

type Props = {
  name: string;
}
function MyComponent({ name }: PropsWithChildren<Props>): React.ReactNode {
  return <h1>{children}, {name}!</h1>
}

Comments

I don't know if this got updated on the TS side somewhere along the way or not, but I noticed the React.FC implicitly comes with a children property typed as the argument. So, you can simplify your examples in this article even further:

type Props = {
	name: string
}

const MyComponent: React.FC<**Props**> = ({ name, children }) => (
	<h1>
		{children}, {name}!
	</h1>
)

// **is equivalent to...**
type Props = {
	name: string
}

const MyComponent: React.FC<**React.PropsWithChildren<Props>**> = ({name, children}) => (
	<h1>
		{children}, {name}!
	</h1>
)

image

https://github.com/Microsoft/TypeScript/issues/22063

이것은 일종의 추악한 해결책처럼 보이므로, 현재의 관용구는 단지 이런 경우에 화살표 기능을 선호하는 것으로 보인다. 그러나 이는 일반적으로 최상위 함수에 대한 const 표현식보다 function 선언을 선호하는 팀에 불일치를 초래한다. 개인적으로 저는 코드 내 어디에나 있는 const를 보는 것보다 최상위 함수에 대한 function이라는 단어를 보는 것이 더 가독성이 있습니다. 심지어 나의 선호도를 공유하는 팀들을 위한 ESLint 규칙도 있다: https://eslint.org/docs/rules/func-style. 어쨌든, 나는 다른 사람들이 비슷한 견해와 최상위 기능들을 위해 여전히 function 키워드를 선호하는 다른 코드베이스(예를 들어 페이스북과 아폴로의 일부 포함)를 표현하는 것을 본 적이 있다.

그러나 스타일상 최상위 함수가 어떤 곳은 선언(using function)으로 선언되고 다른 곳은 표현식(using const)으로 선언되는 경우에도 문제가 됩니다. 그러나 일관성을 원하는 사람들에게 TypeScript는 **위에서 설명한 문제들로 인해** 기본적으로 표현식의 사용을 강요하고 있다.

이것은 물론 최우선 순위와는 거리가 멀지만, 나는 TypeScript가 함수 선언을 위한 일부 동등한 타이핑 구문을 제공하지 않는 것을 보고 놀랐다. (미래에는 멀더라도) 향후 버전에 대해 고려할 수 있다면 좋을 것입니다. 읽어주셔서 감사합니다!

📝 팀 규칙

🐛 트러블 슈팅

Test 관련 이슈
Next.js 관련 이슈
React 관련 이슈
Git 관련 이슈
기타 이슈

🧑‍💻 개발

기술공유
  • 레퍼런스
  • 📆 회의록

    데일리
    Clone this wiki locally