React の children の型がコードレビューの時に { children: JSX.Element | null }
って書かれてて、自分は ReactNode
って書くことが多かったのでどっちが良いんだろう?と自信なかったのでググったのメモ書き
結論: children の型は React.ReactNode で良さそう
React.ReactNode
は JSX.Element
を内包していて、JSX.Element
単体よりカバーできる範囲が広いので React の children の型は React.ReactNode
にしておけば良さそう。
ReactNode, JSX.Element の型を見てみる
- react
17.0.2
React.ReactNode
の型
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined; type ReactFragment = {} | Iterable<ReactNode>; type ReactChild = ReactElement | ReactText; interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> { type: T; props: P; key: Key | null; } type ReactText = string | number; interface ReactPortal extends ReactElement { key: Key | null; children: ReactNode; }
JSX.Element
の型
declare global { namespace JSX { interface Element extends React.ReactElement<any, any> { } // ...
JSX.Element is a ReactElement, with the generic type for props and type being any. It exists, as various libraries can implement JSX in their own way, therefore JSX is a global namespace that then gets set by the library,
<p> // <- ReactElement = JSX.Element <Custom> // <- ReactElement = JSX.Element {true && "test"} // <- ReactNode </Custom> </p>cf. javascript - When to use JSX.Element vs ReactNode vs ReactElement? - Stack Overflow
JSX.Element
= ReactElement
ということらしい。
ReactElement
は ReactChild
型に内包されていて、ReactChild
は ReactNode
型に含まれている。
JSX.Element ⊂ React.ReactNode
になっているっぽい
📝 <Container>
で囲って children で渡した方がパフォーマンス良くなるらしい
A simple composition trick to avoid re-rendering a component. pic.twitter.com/l6eckBgvU5
— Alex Sidorenko (@asidorenko_) February 5, 2022
[参考]
- reactjs - TypeScript and React - children type? - Stack Overflow
- javascript - When to use JSX.Element vs ReactNode vs ReactElement? - Stack Overflow
- 【検証】React.FC と React.VFC はべつに使わなくていい説 – KRAY Inc.
- TypeScript React JSX.Element にハマる - かもメモ
タイトルだけ知ってたけど、1巻と60巻とで表紙のデザインかなり変わってるようなシリーズもあるんですね