반응형
JSX Element, React Element, ReactNode
먼저 JSX가 createElement로 변환되는 것을 한번 보자
return <div>hi</div>;
위 JSX 코드는 다음과 같이 변환된다.
return React.createElement('div', null, 'hi');
JSX Element와 React Element의 관계
JSX문법으로 적는 return <div>hi</div>는 react와 컴파일러에 의해 JS인 createElement로 변환된다.
이 createElement를 통해 생성되는 element가 바로 가상돔의 표현방식인 React Element이다.
실제로 타입을 보았을때는 JSX Element가 React Element보다 조금 더 유연한 방식이다 정도로만 느껴진다.
이 타입은 React Element의 타입인데 매개변수의 타입이 명시되어 있다.
interface ReactElement<
P = any,
T extends string | JSXElementConstructor<any> =
| string
| JSXElementConstructor<any>
> {
type: T;
props: P;
key: Key | null;
}
한편, JSX Element는 React Element의 제너릭에 any를 넣어준것이다.
그러니 JSX Element와 React Element의 관계를 정리하면
- 우리가 Sugar 문법으로 JSX Element 를 작성한다.
- JSX는 react와 컴파일러에 의해 JS인 createElement로 변환되는데 createElement를 통해 생성되는 element가 React Element이다.
- 이 React Element는 가상돔의 표현방식이다.
ReactNode
그럼, ReactNode는 뭘까?
컴포넌트의 children에는 element, string, null, React.Fragment 등등 여러가지가 올 수 있는데 이 children의 type이 ReactNode이다.
interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {}
type ReactNode =
| ReactElement
| string
| number
| Iterable<ReactNode>
| ReactPortal
| boolean
| null
| undefined
// 이건뭐지ㅣ... ㅋㅋㅋ
| DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[
keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES
];
반응형
'개발 > React' 카테고리의 다른 글
jsx의 const 변수를 컴포넌트로 변환하려 성능최적화 하는 아티클 (0) | 2024.06.07 |
---|---|
함수 컴포넌트와 클래스 컴포넌트 (0) | 2024.01.11 |
객체를 state로 이용할 때는 readonly로 직접 변경 못하게 막기 (0) | 2024.01.07 |
state 업데이트는 비동기라기보다는 스냅샷이다. (1) | 2024.01.07 |
zustand에서 functional update가 가능한 setState만들기 (0) | 2023.11.06 |