A collection of powerful, ready-to-use React hooks in TypeScript to streamline your development
npm install oreactoA collection of powerful, ready-to-use React hooks in TypeScript to streamline your development. From AI integrations with FREE providers to infinite scrolling and smart search - build modern React apps faster!
š¤ AI Hooks - Add AI to your app in minutes with FREE providers (Groq, Hugging Face, Together AI)!
- useAI - Simple prompt ā response
- useAIChat - ChatGPT-like interfaces with conversation history
- useAIStream - Real-time streaming for advanced use cases
No complicated setup, no expensive APIs - just free, fast AI for your React apps!
Install the package via npm:
``bash`
npm install oreacto
ā Complete Documentation - Comprehensive guides for all hooks
Individual Hook Guides:
- useRouteTitle - Format titles from URL paths
- useSmartOSearch - Filter and sort lists
- useInfiniteScroll - Infinite scrolling
- useDynamicFields - Dynamic form fields
- useAsync - Async state management
- useAI - Simple AI integration
- useAIChat - ChatGPT-like interfaces
- useAIStream - Real-time AI streaming
AI Setup:
- FREE API Keys Setup ā Get your free AI keys in 2 minutes!
Generate a formatted title based on the current URL path, perfect for setting page titles or breadcrumb labels.
Usage:
`typescript
import { useRouteTitle } from "oreacto";
const MyComponent = () => {
const title = useRouteTitle();
return
$3
Filter and sort a list based on search queries with lodash-powered flexibility. Customize search keys, sorting, and order for dynamic list rendering.
Usage:
`typescript
import { useSmartOSearch } from "oreacto";const MyComponent = ({ items }) => {
const { filteredItems, query, setQuery } = useSmartOSearch({
items,
filterKeys: ["name", "email"], // Filter based on name and email fields
searchQuery: "",
sortKey: "name",
sortOrder: "asc",
});
return (
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
{filteredItems.map((item) => (
- {item.name}
))}
);
};
`$3
Easily implement infinite scrolling by detecting when a user reaches the end of a list and automatically fetching more data.
Usage:
`typescript
import { useInfiniteScroll } from "oreacto";const MyComponent = ({ fetchData, hasMoreData }) => {
const { loader, page, setPage } = useInfiniteScroll({
fetchData,
hasMoreData,
});
return (
{/ Render list content /}
{/ Loader element for triggering infinite scroll /}
);
};
`$3
Generate dynamic field objects based on a parent value. Useful for rendering dynamic forms or repeating fields based on user input.
`typescript
import { useDynamicFields } from "oreacto";const MyComponent = ({ parentValue }) => {
const dynamicFields = useDynamicFields(parentValue, "items", {
label: "Item",
value: "",
});
return (
{dynamicFields.map((field) => (
))}
);
};
`$3
Complete async state management with built-in loading states, error handling, retry logic, and caching. Perfect for API calls and data fetching.
`typescript
import { useAsync } from "oreacto";const MyComponent = () => {
const { data, loading, error, execute, retry } = useAsync(
async (userId) => {
const response = await fetch(
/api/users/${userId});
if (!response.ok) throw new Error("Failed to fetch user");
return response.json();
},
{
retryCount: 3,
retryDelay: 1000,
onSuccess: (user) => console.log("User loaded:", user),
onError: (error) => console.error("Failed:", error),
}
); return (
{loading && Loading...
}
{error && Error: {error.message}
}
{data && Hello, {data.name}!
}
);
};
`$3
The simplest way to add AI to your React app! Just pass a prompt and get a response. Works with FREE AI providers (Groq, Hugging Face, Together AI).
Basic Usage:
`typescript
import { useAI } from "oreacto";const MyComponent = () => {
const { response, loading, sendPrompt } = useAI({
provider: "groq", // FREE! Get key from https://console.groq.com
apiKey: "gsk_...",
});
return (
{loading && Thinking...
}
{response && {response}
}
);
};
`Supported FREE Providers:
- Groq (ā” Fastest) - Get free API key at console.groq.com
- Hugging Face (š¤ Most models) - Get free token at huggingface.co/settings/tokens
- Together AI (šŖ Powerful) - Get free API key at api.together.xyz
> š Complete FREE API Keys Setup Guide - Get your free AI API keys in 2 minutes!
$3
Build ChatGPT-like interfaces with conversation history management.
`typescript
import { useAIChat } from "oreacto";const ChatApp = () => {
const [input, setInput] = useState("");
const { messages, loading, sendMessage, clearChat } = useAIChat({
provider: "groq",
apiKey: process.env.GROQ_API_KEY,
systemPrompt: "You are a helpful coding assistant.",
});
const handleSend = async () => {
await sendMessage(input);
setInput("");
};
return (
{messages.map((msg, i) => (
{msg.content}
))}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && handleSend()}
/>
);
};
`$3
Stream AI responses in real-time for OpenAI, Anthropic, or any streaming API. Perfect for advanced use cases with token-by-token streaming.
> š Complete Hook Guide | Advanced Examples
Basic Usage:
`typescript
import { useAIStream } from "oreacto";const ChatComponent = () => {
const { data, isStreaming, startStream, abort } = useAIStream({
url: "/api/ai/chat",
body: {
prompt: "Tell me a story",
},
});
return (
{data}
{isStreaming ? (
) : (
)}
);
};
`OpenAI Integration:
`typescript
const { data, isStreaming, startStream, abort, error } = useAIStream({
url: "https://api.openai.com/v1/chat/completions",
headers: {
Authorization: Bearer ${YOUR_API_KEY},
"Content-Type": "application/json",
},
body: {
model: "gpt-4",
stream: true,
messages: [{ role: "user", content: "Hello!" }],
},
parseChunk: (chunk) => {
// Parse OpenAI's Server-Sent Events format
if (chunk.startsWith("data: ")) {
const data = chunk.slice(6);
if (data === "[DONE]") return null;
try {
const json = JSON.parse(data);
return json.choices?.[0]?.delta?.content || null;
} catch {
return null;
}
}
return null;
},
onComplete: (fullText) => {
console.log("Stream completed:", fullText);
},
});// Override config at runtime
const handleSubmit = (userMessage: string) => {
startStream({
body: {
...baseConfig,
messages: [{ role: "user", content: userMessage }],
},
});
};
`Advanced Usage with Callbacks:
`typescript
const { data, isStreaming, isComplete, reset } = useAIStream({
url: "/api/stream",
onChunk: (chunk) => {
// Process each chunk (e.g., play sound, analytics)
console.log("Received chunk:", chunk);
},
onComplete: (fullText) => {
// Save to database, show notification, etc.
saveToHistory(fullText);
},
onError: (error) => {
// Handle errors gracefully
showErrorNotification(error.message);
},
});
`API Reference
$3
- Description: Generates a formatted title based on the last segment of the URL.
- Returns:
string - The formatted title.$3
- Parameters:
-
items (Array): List of items to search and sort.
- filterKeys (Array): Keys to apply the search filter.
- searchQuery (string): Initial search query.
- sortKey (string): Key to sort items by.
- sortOrder ('asc' | 'desc'): Sort order.- Returns:
{ filteredItems, query, setQuery }
- filteredItems (Array): Filtered and sorted items.
- query (string): Current search query.
- setQuery (function): Update function for the search query.$3
- Parameters:
-
fetchData (function): Function to fetch data based on the current page.
- hasMoreData (boolean): Indicates if more data is available.- Returns:
{ loader, page, setPage } -
loader (ref): Ref for the element that triggers loading more items.
- page (number): Current page number.
- setPage (function): Manually update the page number.$3
- Parameters:
-
parentValue (number | undefined): Number of fields to generate.
- fieldName (string): Base name for the generated fields.
- fieldTemplate (object): Template object for each field.- Returns:
Array