Basic Usage
Simple Example
Wrap your content with UIStates and provide data, loading, and error states:
typescript
import { UIStates } from "@promise-inc/ui-states";import { useState, useEffect } from "react";
function UserProfile() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
useEffect(() => { fetch("/api/user") .then(res => res.json()) .then(data => { setData(data); setLoading(false); }) .catch(err => { setError(err); setLoading(false); }); }, []);
return ( <UIStates data={data} loading={loading} error={error}> <div className="space-y-4"> <h1 className="text-2xl font-bold">{data.name}</h1> <p className="text-gray-600">{data.email}</p> <p>{data.bio}</p> </div> </UIStates> );}How It Works
- First render: loading is true, UIStates shows a default skeleton
- Data loads: loading becomes false, your content renders
- UI States measures the DOM and saves the structure
- Next time: UI States shows a skeleton matching your exact layout
Props Overview
| Prop | Type | Required | Description |
|---|---|---|---|
| data | unknown | Yes | The data to render (null/undefined during loading) |
| loading | boolean | Yes | Whether data is currently loading |
| error | Error | null | No | Error object if fetch failed |
| children | ReactNode | Yes | Content to render when data exists |
State Flow
typescript
// Loading state (data is null, loading is true)<UIStates data={null} loading={true}> {/* Not rendered yet */}</UIStates>// Shows: Skeleton loading state
// Success state (data exists, loading is false)<UIStates data={user} loading={false}> <div>{user.name}</div></UIStates>// Shows: Your actual content
// Error state (error exists, loading is false)<UIStates data={null} loading={false} error={error}> <div>{user.name}</div></UIStates>// Shows: Error state with retry optionEmpty State
By default, if data is an empty array, UIStates shows an empty state:
typescript
<UIStates data={[]} loading={false}> {data.map(item => ( <div key={item.id}>{item.name}</div> ))}</UIStates>// Shows: "No items found" empty stateFor more advanced usage with TanStack Query, custom states, and skeleton caching, see the Guides section.