はじめに
Reactアプリケーションの開発において、適切な型定義は非常に重要です。特に、複数のコンポーネント間でPropsやステート管理を行う場合、型の一貫性を保つことは保守性と開発効率に大きく影響します。
最近、個人プロジェクトで複数のコンポーネント間の型定義が散在し、少しでも改善できないかと考えました。この記事では、その問題をどのように解決したのか、具体的な実装例と共に解説します。
変更前
client/features/chat/Chat.tsx
export const Chat = ({
setKeyword,
resetChat,
setResetChat,
}: {
setKeyword: (keyword: string) => void;
resetChat: boolean;
setResetChat: (reset: boolean) => void;
}) => {
client/features/news/News.tsx
export const News = ({ query }: { query: string }) => {
client/hooks/useChat.tsx
export const useChat = ({
setKeyword,
resetChat,
setResetChat,
}: {
setKeyword: (keyword: string) => void;
resetChat: boolean;
setResetChat: (reset: boolean) => void;
}) => {
client/hooks/useNews.tsx
export const useNews = ({ query }: { query: string }) => {
上記は変更前の実装で、カスタムフックとコンポーネントで同様の型定義をしています。この方法では、コードが冗長で見にくく、一貫性がありません。これを以下のように修正しました。
変更後
client/features/chat/Chat.tsx
import type { ChatProps } from 'utils/types';
import React from 'react';
export const Chat: React.FC<ChatProps> = ({ setKeyword, resetChat, setResetChat }) => {
client/features/news/News.tsx
import React from 'react';
import type { NewsProps } from 'utils/types';
export const News: React.FC<NewsProps> = ({ query }) => {
client/hooks/useChat.tsx
import type { ChatProps } from 'utils/types';
export const useChat = ({ setKeyword, resetChat, setResetChat }: ChatProps) => {
client/hooks/useNews.tsx
import type { NewsProps } from 'utils/types';
export const useNews = ({ query }: NewsProps) => {
client/utils/types.ts
export interface NewsProps {
query: string;
}
export interface ChatProps {
setKeyword: (keyword: string) => void;
resetChat: boolean;
setResetChat: (reset: boolean) => void;
}
このように実装することで
- Props型定義の一貫性の確保
- React.FCを活用した型安全性の向上
- 保守性と可読性の改善
- 重複する型定義の削減
React.FCをわざわざimportしているのは、コンポーネントとして明確にするためであり、個人的な好みでもあります。
さいごに
まだまだ知らないことばかりですが、少しずつでもこのようにアウトプットしていくことが大切だと感じています。さらに改善点や間違いなどがあれば、気軽にコメントをお待ちしております!