CodeRespite
Back to Templates
Boilerplates: Frontend

React Functional Component Starter

Copy-ready structured TypeScript React functional component managing hooks, async data fetching, and prop interfaces.

UserProfile.tsx
import React, { useState, useEffect } from 'react';

// Standard TypeScript Props Interface
interface UserProfileProps {
  userId: string;
  theme?: 'dark' | 'light';
}

export default function UserProfile({ userId, theme = 'dark' }: UserProfileProps) {
  const [profile, setProfile] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    async function fetchProfile() {
      setLoading(true);
      try {
        const res = await fetch(`/api/users/${userId}`);
        const data = await res.json();
        setProfile(data);
      } catch (err) {
        console.error('Failed to load profile:', err);
      } finally {
        setLoading(false);
      }
    }
    fetchProfile();
  }, [userId]);

  if (loading) return <div className="animate-pulse p-4 text-center">Loading profile...</div>;
  if (!profile) return <div className="p-4 text-red-500">Profile data not found.</div>;

  return (
    <div className={`p-6 rounded-xl border ${theme === 'dark' ? 'bg-zinc-900 border-zinc-800' : 'bg-white border-zinc-200'}`}>
      <h2 className="text-lg font-bold">{profile.name}</h2>
      <p className="text-sm text-zinc-500">{profile.email}</p>
    </div>
  );
}