Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

@galiprandi/react-tools

✨ Simple, composable & accessible utilities for React development.

Logo

NPM DownloadsJSR VersionGitHub Stars

🧠 Overview

@galiprandi/react-tools is a lightweight, dependency-free utility library for React. It provides reusable components and hooks to simplify development and improve accessibility — no configuration needed.

👉 Live Playground


🚀 Installation

npm install @galiprandi/react-tools
# or
yarn add @galiprandi/react-tools
# or
pnpm add @galiprandi/react-tools

AI Agent Skill

Install this library as an AI agent skill for Claude Code, Cursor, Windsurf, and other AI coding agents:

npx skills add https://github.com/galiprandi/skills --skill react-tools

This provides comprehensive guidance for using @galiprandi/react-tools with AI agents.


✨ What's New

3.10.0

Bug Fixes

  • useAI: Fixed isApiAvailable('prompt') returning false in Chrome 140+ — the 'prompt' API type now maps to window.LanguageModel (the actual Chrome global) with legacy fallbacks (window.ai.languageModel, window.ai.LanguageModel, window.PromptAPI) for older Chrome versions. The global lookup is now centralized in a single resolveGlobalApi helper, eliminating the duplicated switch that caused the bug. (#104)
  • Form: Fixed the onSubmit prop being overwritten by the internal handler — user-provided onSubmit is now preserved and called correctly.
  • AsyncBlock: Synchronous errors thrown by promiseFn are now caught and routed to the error state instead of crashing. Timeout detection now uses signal.reason for more accurate abort-vs-timeout discrimination.
  • useAIRewriter / useAIWrite / useLanguageDetection: AbortError no longer leaks the 'error' status — these hooks now reset to 'idle' on abort, consistent with the other AI hooks.
  • useDebounce: Fixed incorrect debounce behavior on the first run by tracking isFirstRun.

Security Hardening

  • useAIProofreader: Added base-constructor validation (Object/Array/Function) to prevent false-positive API detection from polyfills or prototype tampering.
  • useTranslator: Added base-constructor validation for both Translator and LanguageDetector globals, and extracted the supported-languages list into a SUPPORTED_LANGUAGES constant (eliminating duplication).
  • useLanguageDetection: Added base-constructor validation for LanguageDetector.

API Change

  • AsyncBlock: The error prop is now optional (error?). Previously required, it is now consistent with the pending prop which was already optional when using a function form.

Developer Experience

  • Added displayName to all components (AsyncBlock, DateTime, Form, Input, Observer, LazyRender) for better React DevTools introspection.
  • Improved JSDoc across useAI, useAIPrompt, useAIProofreader, useAISummarize, useList, AsyncBlock, and Input.
  • Added dedicated coverage test files for useAISummarize, useAIProofreader, and expanded coverage for useTranslator.

Previous: AI Hooks

AI Hooks - New hooks for browser-native AI features using Chrome's AI API:

  • useAI - Check and manage availability of browser's AI APIs
  • useAISummarize - Generate text summaries with streaming support
  • useLanguageDetection - Detect language from text with confidence scores
  • useTranslator - Translate text between languages with streaming support
  • useAIPrompt - Generate AI responses using Chrome's Prompt API (Gemini Nano)
  • useAIWrite - Generate written content with customizable tone and format
  • useAIRewriter - Rewrite and restructure text with customizable tone, format, and length
  • useAIProofreader - Check grammar and spelling with highlighted corrections

📚 Table of Contents

📦 Components

AsyncBlock

Description
Declarative component to render async data with loading, success, and error states. Automatically cancels in-flight requests when dependencies change.

Example

<AsyncBlockpromiseFn={()=>fetch(`/api/user`).then(res=>res.json())}pending={<p>Loading...</p>}success={(data,reload)=>(<div><p>Welcome {data.name}</p><buttononClick={reload}>Refresh</button></div>)}error={(err,reload)=>(<div><p>Error: {(errasError).message}</p><buttononClick={reload}>Retry</button></div>)}timeOut={5000}deps={[userId]}/>

Props

PropTypeDescription
promiseFn(signal?: AbortSignal) => Promise<T>Async function returning a Promise
pendingReactNode | (reload: () => void) => ReactNodeUI while loading
success(data: T, reload: () => void) => ReactNodeUI on success
error(err: unknown, reload: () => void) => ReactNodeUI on error
timeOutnumberOptional timeout in ms
depsany[]Dependency list for re-execution
onSuccess(data: T) => voidOptional success callback
onError(err: unknown) => voidOptional error callback

Form

Description
Enhanced <form> element that automatically gathers and returns values on submit.

Example

<Form<{username: string}>onSubmitValues={console.log}filterEmptyValues><Inputname="username"label="Username"/><buttontype="submit">Submit</button></Form>

Props

PropTypeDescription
onSubmitValues(values: T) => voidHandles form submission with collected values
filterEmptyValuesboolean(default: false)Remove empty fields before submission

Input

Description
Custom input component supporting transformations, debounce, datalist, and more.

Example

<Inputlabel="Email"name="email"placeholder="Enter your email"transform="onlyEmail"onChangeValue={(val)=>console.log(val)}debounceDelay={500}/>// Multiple transforms applied sequentially<Inputlabel="Username"transform={['toUpperCase','onlyAlphanumeric']}onChangeValue={(val)=>console.log(val)}/>

Props

PropTypeDescription
labelstringOptional label
transformstring | string[] ("camelCase", "pascalCase", "kebabCase", "titleCase", "slugify", "onlyEmail"...)Built-in value transforms (single or array for sequential application)
transformFn(value: string) => stringCustom value transform
onChangeValue(value: string) => voidFires on value change
onChangeDebounce(value: string) => voidFires after debounce
debounceDelaynumberDelay in milliseconds
dataliststring[]List of autocomplete suggestions

DateTime

Description
A wrapper around <input type="datetime-local" /> that handles ISO string conversion.

Example

<DateTimelabel="Appointment"isoValue={value}onChangeISOValue={setValue}/>

Props

PropTypeDescription
isoValuestringISO 8601 datetime value
onChangeISOValue(iso: string) => voidCallback with ISO string
isoMinstringMinimum date/time in ISO 8601 format
isoMaxstringMaximum date/time in ISO 8601 format
...InputPropsAll <Input /> propsInherits all Input behavior

Dialog

Description
Accessible dialog/modal component built on top of the native <dialog> element.

Example

<Dialogbehavior="modal"opener={<button>Open Modal</button>}onClose={()=>console.log('Closed')}><p>This is a dialog!</p></Dialog>

Props

PropTypeDescription
isOpenbooleanControlled open state (optional)
behavior'dialog' | 'modal'Dialog type (default: 'modal')
onOpen() => voidTriggered on open
onClose() => voidTriggered on close
openerReactNodeElement to trigger opening
childrenReactNodeContent inside the dialog
closeOnBackdropClickboolean (default: false)Whether to close when clicking the backdrop
...dialogPropsAll native <dialog> propsInherits all HTML dialog element attributes

Observer

Description
Tracks whether a child element is visible in the viewport using IntersectionObserver. Triggers callbacks when the element appears or disappears from the viewport.

Example

<Observerwrapper="section"onAppear={()=>console.log('Element appeared')}onDisappear={()=>console.log('Element disappeared')}threshold={0.5}><div>Watch me appear!</div></Observer>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
onAppear(entry: IntersectionObserverEntry) => voidCallback when element appears in viewport
onDisappear(entry: IntersectionObserverEntry) => voidCallback when element disappears from viewport
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


LazyRender

Description
Only renders children when they become visible in the viewport. Automatically unmounts children when they disappear to optimize performance.

Example

<LazyRenderwrapper="section"placeholder={<span>Loading...</span>}threshold={0.5}><imgsrc="/heavy-image.jpg"alt="Lazy"/></LazyRender>

Props

PropTypeDescription
wrapperkeyof ReactHTML (default: 'div')HTML element to wrap children with
placeholderReactNodeRendered before children become visible
thresholdnumber | number[]Intersection threshold (0-1)
rootElement | nullThe element used as the viewport
rootMarginstringMargin around the root

Note: This component extends IntersectionObserverInit, accepting all standard Intersection Observer options.


🪝 Hooks

useAI

Description
Hook for checking and managing the availability of browser's AI APIs. This hook provides a centralized way to detect which AI APIs are available, track model download progress, and preload models for faster initial use. Supports current APIs (Summarizer, Translator, LanguageDetector) and experimental APIs (Prompt, Writer, Rewriter, Proofreader).

Example

import{useAI}from'@galiprandi/react-tools';functionMyComponent(){// Check all APIsconst{ isAvailable, apis, status }=useAI();// Check specific APIsconst{ isAvailable, apis, preload }=useAI({apis: ['translator','summarizer']});// Preload modelsuseEffect(()=>{if(isAvailable){preload('translator');}},[isAvailable,preload]);// Show download progressif(apis.translator.availability==='downloading'){constprogress=apis.translator.progress;return<LoadingBar{...progress}/>;}}

Options

OptionTypeDefaultDescription
apisAIApiType[]All APIsSpecific APIs to check. If not provided, checks all APIs
onProgress(api: AIApiType, progress: { loaded: number; total: number }) => void-Callback when an API's download progress updates
onReady(api: AIApiType) => void-Callback when an API becomes ready

Returns

PropertyTypeDescription
isAvailablebooleanWhether any of the requested APIs are available
status'idle' | 'loading' | 'ready' | 'error'The current status of the availability check
errorError | nullError object if the check failed
apisRecord<AIApiType, AIApiStatus>Status of each API
isApiAvailable(api: AIApiType) => booleanCheck if a specific API is available
getApiProgress(api: AIApiType) => { loaded: number; total: number } | nullGet download progress for a specific API
preload(api: AIApiType) => Promise<void>Preload a specific API's model
preloadAll() => Promise<void>Preload all APIs' models

Supported APIs

summarizer, translator, languageDetector, prompt (Experimental), writer (Experimental), rewriter (Experimental), proofreader (Experimental)

Note: This hook requires Chrome's Native AI APIs, which are currently experimental and may not be available in all browsers.

Prompt API mapping: The prompt API type maps to Chrome's window.LanguageModel global (the Prompt API / Gemini Nano). For backwards compatibility, the hook also falls back to the legacy window.ai.languageModel, window.ai.LanguageModel, and window.PromptAPI exposure paths. This keeps useAI consistent with useAIPrompt, which performs the same lookup.


useAISummarize

Description
Hook for using the browser's AI Summarizer API. This hook provides a React interface to Chrome's native AI Summarizer API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount.

Example

import{useAISummarize}from'@galiprandi/react-tools';functionMyComponent(){constsummarize=useAISummarize({type: 'tldr',format: 'markdown',length: 'short',outputLanguage: 'en',streaming: true});consthandleSummarize=async()=>{awaitsummarize.summarize(longText,'End the summary with: Powered by my app');console.log(summarize.data);};return(<div><buttononClick={handleSummarize}>Summarize</button>{summarize.status==='summarizing'&&<p>Summarizing...</p>}{summarize.data&&<p>{summarize.data}</p>}</div>);}

Options

OptionTypeDefaultDescription
type'tldr' | 'key-points' | 'teaser' | 'headline'undefinedType of summary to generate
format'plain-text' | 'markdown'undefinedOutput format of the summary
length'short' | 'medium' | 'long'undefinedLength of the summary
sharedContextstringundefinedShared context for all summaries
expectedInputLanguagesstring[]undefinedExpected input languages (BCP 47 format)
outputLanguage'en' | 'es' | 'ja' | 'auto' | 'user''auto'Output language. Use 'auto' to detect from text (default), 'user' for browser language, or specify a language code
expectedContextLanguagesstring[]undefinedExpected context languages (BCP 47 format)
preference'auto' | 'capability''auto'Performance preference (auto or capability)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on mount for faster first summary

Returns

PropertyTypeDescription
datastringThe generated summary text
status'idle' | 'initializing' | 'downloading' | 'summarizing' | 'success' | 'error'Current status of the summarization process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if summarization failed
supportedPreferences('auto' | 'capability')[]Supported preference values based on browser capabilities
summarize(text: string, context?: string) => Promise<void>Function to summarize text with optional context instruction
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's AI Summarizer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useLanguageDetection

Description
Hook for using the browser's Language Detection API. This hook provides a React interface to Chrome's native Language Detection API. It handles model initialization, download progress, and automatic cleanup on unmount. Returns the most likely detected language, confidence score, all results, and user language comparison.

Example

import{useLanguageDetection}from'@galiprandi/react-tools';functionMyComponent(){const{ lang, confidence, allLangs, userLang, isUserLang, status }=useLanguageDetection({text: 'Hallo und herzlich willkommen!',minConfidence: 0.8});return(<div>{status==='detecting'&&<p>Detecting...</p>}{lang&&(<p>
Detected: {lang} ({Math.round(confidence!*100)}% confidence)
{isUserLang&&<span> (matches your language)</span>}</p>)}{allLangs.length>1&&(<details><summary>All detected languages</summary><ul>{allLangs.map(({ lang, confidence })=>(<likey={lang}>{lang}: {Math.round(confidence*100)}%</li>))}</ul></details>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to detect language from. Re-detects automatically when changed
enablebooleantrueEnable/disable auto-detection
warmupbooleantruePreload model on component mount for faster first detection
minConfidencenumber0Minimum confidence to include in allLangs (0.0 - 1.0)
maxResultsnumber-Maximum number of results to return in allLangs

Returns

PropertyTypeDescription
langstring | undefinedThe most likely detected language code (e.g., 'en', 'es')
confidencenumber | undefinedConfidence of the most likely detection (0.0 - 1.0)
allLangsDetectionResult[]All detected languages with confidence scores, ranked from most to least likely
userLangstringUser's browser language code (e.g., 'en', 'es')
isUserLangbooleanWhether the detected language matches the user's browser language
status'idle' | 'initializing' | 'downloading' | 'detecting' | 'success' | 'error'Current status of the detection process
progress{ loaded: number, total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if detection failed
reset() => voidFunction to reset the hook state

Note: This hook requires Chrome's Language Detection API, which is currently experimental and may not be available in all browsers.


useTranslator

Description
Hook for using the browser's Translator API. This hook provides a React interface to Chrome's native Translator API. It handles model initialization, download progress, streaming support, and automatic cleanup on unmount. Supports 38+ languages. Automatically detects source language and uses browser language by default. Optimization: When the detected source language matches the target language, the hook returns the original text without loading the translation model.

Example

import{useTranslator}from'@galiprandi/react-tools';functionMyComponent(){// Auto-detect source language and translate to browser languageconst{ data, detectedSourceLanguage, resolvedTargetLanguage, status }=useTranslator({text: 'Hello world, how are you?'});return(<div>{status==='translating'&&<p>Translating...</p>}{data&&(<p>{data}{detectedSourceLanguage&&<small> (from {detectedSourceLanguage} to {resolvedTargetLanguage})</small>}</p>)}</div>);}

Options

OptionTypeDefaultDescription
textstring-Text to translate. Auto-translates when changed
sourceLanguage'auto' | SupportedLanguage'auto'Source language code. Use 'auto' to detect from text automatically
targetLanguage'user' | SupportedLanguage'user'Target language code. Use 'user' for browser language
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first translation
enablebooleantrueEnable/disable auto-translation

Returns

PropertyTypeDescription
datastringThe translated text
detectedSourceLanguagestring | undefinedDetected source language (when sourceLanguage is 'auto')
resolvedTargetLanguagestring | undefinedResolved target language (when targetLanguage is 'user')
status'idle' | 'initializing' | 'downloading' | 'translating' | 'success' | 'error'Current status of the translation process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if translation failed
translate(text: string) => Promise<void>Function to translate text manually
reset() => voidFunction to reset the hook state

Supported Languages

ar, bg, bn, cs, da, de, el, en, es, fi, fr, hi, hr, hu, id, it, iw, ja, kn, ko, lt, mr, nl, no, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tr, uk, vi, zh, zh-Hant

Note: This hook requires Chrome's Translator API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIPrompt

Description
Hook for using the browser's Prompt API (Gemini Nano) with multimodal support. This hook provides a React interface to Chrome's native Prompt API with automatic type inference for text, images, and audio. It handles session creation, model download progress, streaming support, context management, and automatic cleanup on unmount. Supports multi-turn conversations with system prompts, custom AI parameters, and multimodal content.

Example

import{useAIPrompt}from'@galiprandi/react-tools';functionMyComponent(){const{ data, prompt, append, status, contextUsage, contextWindow }=useAIPrompt({initialPrompts: [{role: 'system',content: 'You are a helpful assistant.'}],expectedInputs: [{type: 'text'},{type: 'image'}],expectedOutputs: [{type: 'text'}],temperature: 0.7,topK: 40,streaming: true});consthandleSendWithImage=async(imageBlob: Blob)=>{awaitprompt([{role: 'user',content: ['Describe this image:',imageBlob]}]);};consthandleSend=async()=>{awaitprompt('What is the capital of France?');};return(<div><buttononClick={handleSend}disabled={status==='prompting'}>
Send
</button>{status==='prompting'&&<p>Thinking...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}<small>Context: {contextUsage} / {contextWindow} tokens</small></div>);}

Options

OptionTypeDefaultDescription
initialPromptsAIPromptMessage[]-Initial prompts to provide context to the model (system/user/assistant roles)
temperaturenumber-Temperature for sampling (higher is more creative)
topKnumber-Top-K sampling parameter
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first prompt
expectedInputs{ type: 'text' | 'image' | 'audio' }[]-Expected input types for multimodal support (e.g., [{ type: 'text' }, { type: 'image' }])
expectedOutputs{ type: 'text' }[]-Expected output types (e.g., [{ type: 'text' }])

Returns

PropertyTypeDescription
datastringThe AI response text
status'idle' | 'initializing' | 'downloading' | 'prompting' | 'success' | 'error'Current status of the prompt process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if prompting failed
prompt(input: string | AILanguageModelPrompt[]) => Promise<void>Function to send a prompt to the AI (supports text or multimodal content)
append(input: AILanguageModelPrompt[]) => Promise<void>Function to append contextual messages without generating response (useful for preloading images/audio)
reset() => voidFunction to reset the hook state
contextUsagenumberNumber of tokens used in the current session
contextWindownumberMaximum number of tokens allowed in the session

Multimodal Support:

The hook supports automatic type inference for:

  • Text: strings
  • Audio: AudioBuffer, ArrayBuffer, ArrayBufferView, Blob (audio/*)
  • Images: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, VideoFrame, Blob (image/*), ImageData

Important Limitations:

  • Single content type per prompt: The Chrome AI model currently has limitations processing multiple content types (e.g., image + audio) simultaneously in a single prompt. Send one type of multimodal content at a time for best results.
  • Model capability: Multimodal support depends on the specific Chrome AI model version and capabilities available in the browser.

Note: This hook requires Chrome's Prompt API (Gemini Nano), which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIWrite

Description
Hook for using the browser's Writer API to generate written content with customizable tone and format. This hook provides a React interface to Chrome's native Writer API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for generating emails, blog posts, social media content, and other written materials.

Example

import{useAIWrite}from'@galiprandi/react-tools';functionMyComponent(){const{ data, write, status, progress }=useAIWrite({tone: 'formal',format: 'markdown',length: 'medium',sharedContext: 'This is for a professional business email',streaming: true});consthandleWrite=async()=>{awaitwrite('Write a thank you email to a colleague for their help on the project','I want to mention their attention to detail');};return(<div><buttononClick={handleWrite}disabled={status==='writing'}>
Generate
</button>{status==='writing'&&<p>Writing...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'formal' | 'neutral' | 'casual''neutral'Writing tone: formal (professional), neutral (balanced), casual (friendly)
format'markdown' | 'plain-text''markdown'Output format: markdown (formatted) or plain-text
length'short' | 'medium' | 'long''short'Length of the output: short (brief), medium (moderate), long (detailed)
sharedContextstring-Shared context for all writing tasks (helps maintain consistency across multiple writes)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first write

Returns

PropertyTypeDescription
datastringThe generated written content
status'idle' | 'initializing' | 'downloading' | 'writing' | 'success' | 'error'Current status of the writing process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if writing failed
write(prompt: string, context?: string) => Promise<void>Function to generate written content with optional context
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Choose between formal, neutral, or casual writing styles
  • Format Options: Output in markdown or plain-text
  • Length Control: Generate short, medium, or long content
  • Shared Context: Maintain consistency across multiple writing tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Reusable Writer: The same writer instance can be used for multiple writes

Use Cases:

  • Email generation (professional, casual, thank you, follow-up)
  • Blog post writing
  • Social media content creation
  • Document drafting
  • Report generation
  • Marketing copy

Note: This hook requires Chrome's Writer API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIRewriter

Description
Hook for using the browser's Rewriter API to rewrite and restructure text with customizable tone, format, and length. This hook provides a React interface to Chrome's native Rewriter API. It handles model initialization, download progress, streaming support, shared context management, and automatic cleanup on unmount. Perfect for improving writing style, adjusting tone, condensing or expanding content, and restructuring text for different audiences.

Example

import{useAIRewriter}from'@galiprandi/react-tools';functionMyComponent(){const{ data, rewrite, status, progress }=useAIRewriter({tone: 'more-formal',format: 'markdown',length: 'shorter',sharedContext: 'This is for a professional business email',streaming: true});consthandleRewrite=async()=>{awaitrewrite('Hi, I wanted to let you know the project is going well.','Make it more professional');};return(<div><buttononClick={handleRewrite}disabled={status==='rewriting'}>
Rewrite
</button>{status==='rewriting'&&<p>Rewriting...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}</div>);}

Options

OptionTypeDefaultDescription
tone'more-formal' | 'as-is' | 'more-casual''as-is'Writing tone: more-formal (professional), as-is (balanced), more-casual (friendly)
format'as-is' | 'markdown' | 'plain-text''as-is'Output format: as-is (preserve original), markdown (formatted), plain-text
length'shorter' | 'as-is' | 'longer''as-is'Length of the output: shorter (condense), as-is (preserve), longer (expand)
sharedContextstring-Shared context for all rewriting tasks (helps maintain consistency across multiple rewrites)
outputLanguagestring-Output language (BCP 47 format, e.g., 'en', 'es', 'fr')
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format)
expectedContextLanguagesstring[]-Expected context languages (BCP 47 format)
streamingbooleanfalseEnable streaming output for real-time results
warmupbooleantruePreload model on component mount for faster first rewrite

Returns

PropertyTypeDescription
datastringThe rewritten text
status'idle' | 'initializing' | 'downloading' | 'rewriting' | 'success' | 'error'Current status of the rewriting process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if rewriting failed
rewrite(text: string, context?: string, overrideTone?: 'more-formal' | 'as-is' | 'more-casual') => Promise<void>Function to rewrite text with optional context and tone override
reset() => voidFunction to reset the hook state

Features:

  • Multiple Tones: Adjust tone to be more formal, keep as-is, or more casual
  • Format Options: Preserve original format, convert to markdown, or plain-text
  • Length Control: Condense (shorter), preserve (as-is), or expand (longer) content
  • Shared Context: Maintain consistency across multiple rewriting tasks
  • Language Support: Specify expected input/output languages
  • Streaming: Real-time content generation for better UX
  • Tone Override: Override global tone setting per rewrite
  • Reusable Rewriter: The same rewriter instance can be used for multiple rewrites

Use Cases:

  • Email tone adjustment (make more professional or casual)
  • Content condensation (summarize long text)
  • Content expansion (add detail and elaboration)
  • Style improvement (enhance readability and flow)
  • Audience adaptation (rewrite for different audiences)
  • Review polishing (improve feedback constructiveness)
  • Format conversion (convert to markdown or plain-text)

Note: This hook requires Chrome's Rewriter API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useAIProofreader

Description
Hook for using the browser's Proofreader API to check grammar and spelling with highlighted corrections. This hook provides a React interface to Chrome's native Proofreader API. It handles model initialization, download progress, and automatic cleanup on unmount. Perfect for text editing, content review, and improving writing quality.

Example

import{useAIProofreader}from'@galiprandi/react-tools';functionMyComponent(){const{ data, corrections, proofread, status, progress }=useAIProofreader({expectedInputLanguages: ['en'],});consthandleProofread=async()=>{awaitproofread('I seen him yesterday at the store.');};return(<div><buttononClick={handleProofread}disabled={status==='proofreading'}>
Proofread
</button>{status==='proofreading'&&<p>Proofreading...</p>}{status==='downloading'&&<p>Downloading model...</p>}{data&&<p>{data}</p>}{corrections.length>0&&(<ul>{corrections.map((c,i)=>(<likey={i}>{c.type&&<span>Type: {c.type}</span>}{c.explanation&&<span> - {c.explanation}</span>}</li>))}</ul>)}</div>);}

Options

OptionTypeDefaultDescription
expectedInputLanguagesstring[]-Expected input languages (BCP 47 format, e.g., 'en', 'es')
warmupbooleantruePreload model on component mount for faster first proofread

Returns

PropertyTypeDescription
datastringThe corrected text
correctionsProofreadCorrection[]Array of corrections with startIndex, endIndex, type, and explanation
status'idle' | 'initializing' | 'downloading' | 'proofreading' | 'success' | 'error'Current status of the proofreading process
progress{ loaded: number; total: number } | nullDownload progress if model is being downloaded
errorError | nullError object if proofreading failed
proofread(text: string) => Promise<void>Function to proofread text
reset() => voidFunction to reset the hook state

ProofreadCorrection:

  • startIndex: Start index of the correction in the original text
  • endIndex: End index of the correction in the original text
  • type: Type of correction (e.g., 'grammar', 'spelling')
  • explanation: Explanation of the correction

Features:

  • Grammar Checking: Detect and correct grammatical errors
  • Spelling Correction: Identify and fix spelling mistakes
  • Detailed Corrections: Get correction type and explanation for each issue
  • Language Support: Specify expected input languages for better accuracy
  • Fast Proofreading: Warmup option for faster first proofread
  • Reusable Proofreader: The same proofreader instance can be used for multiple checks

Use Cases:

  • Text editing (grammar and spell checking)
  • Content review (improving writing quality)
  • Email validation (catching typos before sending)
  • Document proofreading (ensuring professional quality)
  • Blog post review (improving readability)
  • Comment moderation (identifying language issues)

Note: This hook requires Chrome's Proofreader API, which is currently experimental and may not be available in all browsers. Use the useAI hook to check availability first.


useDebounce

Description
A React hook that returns a debounced version of a value. Useful for search input, filters, etc.

Example

constdebouncedSearch=useDebounce(searchTerm,500);

Props

ParameterTypeDescription
valueTValue to debounce
delaynumberDelay in milliseconds (default: 500)

Returns
Debounced version of the value (T).


useThrottle

Description
A React hook that returns a throttled version of a value. Ensures the value updates at most once every specified limit.

Example

constthrottledValue=useThrottle(value,500);

Props

ParameterTypeDescription
valueTValue to throttle
limitnumberLimit in milliseconds

Returns
Throttled version of the value (T).


useTimer

Description A React hook that abstracts the complexity of managing setTimeout and setInterval directly in React components. It provides automatic cleanup, lifecycle events, flexible scheduling, and simplified control to prevent memory leaks and unexpected behavior.

Features

  • Automatic Cleanup: Timers are automatically cleared when the component using the hook unmounts, preventing memory leaks.
  • Lifecycle Events: Receive notifications when a timer is set, cancelled, completes, or reports progress.
  • Flexible Scheduling: Set timers by milliseconds, a future Date object, or as limited intervals.
  • Simplified Control: Clear any active timer with a single method call.

Example

import{useEffect}from'react';import{useTimer}from'@galiprandi/react-tools';functionFutureExecution({ targetDate }: {targetDate: Date}){const{ setTimeoutDate, clearTimer }=useTimer({onSetTimer: (id)=>console.log(`Timer ID ${id} set for future execution`),onTimerComplete: (id)=>console.log(`Timer ID ${id} completed!`),onCancelTimer: (id)=>console.log(`Timer ID ${id} cancelled!`),onProgress: (progress)=>console.log(`Progress: ${Math.round(progress*100)}%`),});useEffect(()=>{console.log(`Scheduling action for: ${targetDate.toLocaleTimeString()}`);setTimeoutDate(()=>{// Do something here, like a fake fetch requestconsole.log("--- Fake fetch executed! ---");},targetDate);// ⚠️ Remember to clear the timer when the component unmounts or when the targetDate changesreturn()=>{console.log('Component unmounting or targetDate change, clearing timer.');clearTimer();};},[setTimeoutDate,clearTimer,targetDate]);return(<div><p>Check the console for timer messages.</p></div>);}

Parameters (options)

ParameterTypeDescription
onSetTimer(timerId: number) => voidCallback fired when a new timer is successfully set.
onCancelTimer(timerId: number) => voidCallback fired when an active timer is cleared/cancelled.
onTimerComplete(timerId: number) => voidCallback fired when a timer completes naturally (timeout) or for each interval execution (interval/limited interval).
onProgress(progress: number, elapsedMs: number, totalMs: number) => voidCallback fired periodically during long timers (setTimeout) and limited intervals to report progress (0 to 1).

Returns An object containing control methods and status/info getters.

PropertyTypeDescription
setTimeout(callback: () => void, delay: number | Date) => number | nullSets a timeout with event callbacks. Accepts milliseconds or a future Date. Returns the timer ID.
setInterval(callback: () => void, delay: number) => number | nullSets an interval with event callbacks. Accepts milliseconds. Returns the timer ID.
setTimeoutDate(callback: () => void, targetDate: Date) => number | nullSets a timeout to execute at a specific future Date. Returns the timer ID.
setLimitedInterval(callback: () => void, delay: number, iterations: number) => number | nullSets an interval that executes a fixed number of times. Returns the timer ID.
clearTimer() => voidClears any currently active timer set by this hook instance.
isActive() => booleanReturns true if a timer is currently active, false otherwise.
getCurrentTimerId() => number | nullReturns the ID of the currently active timer, or null.
getRemainingIterations() => number | nullFor setLimitedInterval, returns remaining executions.
getRemainingTime() => numberFor an active setTimeout, returns estimated remaining time in ms, otherwise -1.

useList

Description A React hook that simplifies managing array state in components. It provides immutable helper methods for common operations like adding, inserting, removing, updating, finding, and counting items based on index or item properties.

Parameters

ParameterTypeDescription
initialListT[]The initial array state (defaults to [])

Returns An object containing the current array state (list) and helper functions to modify or query it immutably.

PropertyTypeDescription
listT[]The current array state.
addItem(item: T) => voidAdds an item to the end of the array.
prepend(item: T) => voidAdds an item to the beginning of the array.
prependMany(items: T[]) => voidAdds multiple items to the beginning of the array. Does nothing if input is not an array or is empty.
insert(index: number, item: T) => voidInserts an item at the specified index. If the index is out of bounds, the item is added to the beginning (index < 0) or end (index > length).
insertMany(items: T[], index?: number) => voidInserts multiple items at the specified index. Defaults to the end if index is not provided. Does nothing if input is not an array or is empty.
removeByIdx(index: number) => voidRemoves the item at the specified index. If the index is out of bounds, the list remains unchanged.
removeBy(key: string | undefined | null, value: any) => voidRemoves the first item where item[key] strictly equals value. If key is undefined or null, removes the first item where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
removeManyBy(key: string | undefined | null, value: any) => voidRemoves all items where item[key] strictly equals value. If key is undefined or null, removes all items where item strictly equals value (useful for primitives). If no match is found, the list remains unchanged.
updateByIdx(index: number, updateFn: (item: T) => T) => voidUpdates the item at the specified index using an immutable updateFn. If the index is out of bounds, the list remains unchanged.
updateBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates the first item where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no match is found, the list remains unchanged.
updateManyBy(key: string | undefined | null, value: any, updateFn: (item: T) => T) => voidUpdates all items where item[key] strictly equals value (or item === value if key is null/undefined) using an immutable updateFn. If no matches are found, the list remains unchanged.
removeWhere(predicate: (item: T, index: number) => boolean) => voidRemoves all items that match a predicate function. If no match is found, the list remains unchanged.
updateWhere(predicate: (item: T, index: number) => boolean, updateFn: (item: T) => T) => voidUpdates all items that match a predicate function using an immutable updateFn. If no match is found, the list remains unchanged.
unique(key?: string | undefined | null) => voidRemoves duplicate items from the list based on a key or reference comparison. If no duplicates are found, the list remains unchanged.
clearList() => voidRemoves all items from the list, setting it to an empty array.
setList(newList: T[] | ((currentList: T[]) => T[])) => voidReplaces the entire list array, similar to the standard useState setter. Accepts a new array or a function updater.
findItemBy(key: string | undefined | null, value: any) => T | undefinedFinds and returns the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Does not modify the list. Returns undefined if not found.
findItemsBy(key: string | undefined | null, value: any) => T[]Finds and returns all items where item[key] strictly equals value. If key is undefined or null, finds all items where item strictly equals value. Does not modify the list. Returns an empty array if no matches are found.
findIdxBy(key: string | undefined | null, value: any) => numberFinds and returns the index of the first item where item[key] strictly equals value. If key is undefined or null, finds the first item where item strictly equals value. Returns -1 if not found.
contains(key: string | undefined | null, value: any) => booleanChecks if any item matches item[key] === value. If key is undefined or null, checks if item === value. Returns true if found, false otherwise.
count(predicate?: (item: T) => boolean) => numberReturns the total number of items in the list, or the count of items matching an optional predicate. Does not modify the list.
toggle(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or removes it if it is, based on an optional key or reference comparison.
upsert(item: T, key?: string | undefined | null) => voidAdds an item if it's not present, or updates the existing one if it is, based on an optional key or reference comparison.
move(fromIndex: number, toIndex: number) => voidMoves an item from fromIndex to toIndex immutably. If indices are out of bounds or identical, the list remains unchanged.
sort(keyOrCompareFn?: string | ((a: T, b: T) => number) | null, order?: 'asc' | 'desc') => voidSorts the list immutably using an optional key or comparison function, and an optional sort order.
shuffle() => voidRandomly reorders the list items immutably.
swap(indexA: number, indexB: number) => voidSwaps two items in the list immutably based on their indices.
reverse() => voidReverses the order of the items in the list immutably.
rotate(offset: number) => voidRotates the list items by a given offset immutably.

♿ Accessibility & Performance

All components follow accessibility best practices:

  • Dialog uses proper ARIA roles and keyboard focus control.
  • Input supports labeling, aria attributes, and datalists.
  • LazyRender and Observer use IntersectionObserver to optimize rendering.

❓ FAQ

Q: Is this compatible with React Native?
A: No, this library is intended for use in React DOM (web).

Q: Can I style components with Tailwind or CSS modules?
A: Yes, components are unstyled and fully customizable.

Q: Does it support SSR or work in Next.js?
A: Yes, all components are compatible with SSR environments.

Q: How can I report a bug or request a new feature?
A: Open an issue on the GitHub repo.


📄 License

MIT © @galiprandi

About

A set of simple and intuitive utilities for developing React applications.

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages