Utility Reference
Complete TypeScript API reference for all utilities provided by @sparkle/utils.
📱 React Hooks
Section titled “📱 React Hooks”useDebounce
Section titled “useDebounce”Debounces a rapidly changing value to limit how often it updates.
useDebounce Signature
Section titled “useDebounce Signature”function useDebounce<T>(value: T, delay: number): TuseDebounce Generic Parameters
Section titled “useDebounce Generic Parameters”T- The type of the value being debounced
useDebounce Parameters
Section titled “useDebounce Parameters”| Parameter | Type | Description |
|---|---|---|
value | T | The value to debounce |
delay | number | The delay in milliseconds |
useDebounce Returns
Section titled “useDebounce Returns”T- The debounced value
useDebounce Implementation Details
Section titled “useDebounce Implementation Details”- Uses
useStateanduseEffectinternally - Automatically cleans up timers on unmount
- Updates only after the specified delay period has passed without new values
- Preserves the exact type of the input value
useClickOutside
Section titled “useClickOutside”Detects clicks outside of a specified element and executes a callback function.
useClickOutside Signature
Section titled “useClickOutside Signature”function useClickOutside<T extends HTMLElement>( handler: () => void): React.RefObject<T | null>useClickOutside Generic Parameters
Section titled “useClickOutside Generic Parameters”T extends HTMLElement- The type of HTML element to monitor (defaults toHTMLElement)
useClickOutside Parameters
Section titled “useClickOutside Parameters”| Parameter | Type | Description |
|---|---|---|
handler | () => void | Callback function to execute when clicking outside |
useClickOutside Returns
Section titled “useClickOutside Returns”React.RefObject<T \| null>- A ref object to attach to the target element
useClickOutside Implementation Details
Section titled “useClickOutside Implementation Details”- Listens for both
mousedownandtouchstartevents - Automatically removes event listeners on cleanup
- Uses
useRefanduseEffectfor efficient event management - Checks if the clicked element is contained within the ref element
useAsync
Section titled “useAsync”Manages the state of asynchronous operations with loading, error, and execution tracking.
useAsync Signature
Section titled “useAsync Signature”function useAsync<T extends (...args: any[]) => Promise<any>>( asyncFn: T): [boolean, Error | null, (...args: Parameters<T>) => Promise<ReturnType<T>>]useAsync Generic Parameters
Section titled “useAsync Generic Parameters”T extends (...args: any[]) => Promise<any>- The type of the async function
useAsync Parameters
Section titled “useAsync Parameters”| Parameter | Type | Description |
|---|---|---|
asyncFn | T | The async function to manage |
useAsync Returns
Section titled “useAsync Returns”Tuple containing:
boolean- Loading state (true when operation is in progress)Error \| null- Error state (null if no error occurred)(...args: Parameters<T>) => Promise<ReturnType<T>>- Memoized execution function
useAsync Implementation Details
Section titled “useAsync Implementation Details”- Uses
useStatefor loading and error state management - Uses
useCallbackto memoize the execution function - Automatically handles error catching and state updates
- Preserves the exact signature and return type of the input function
- Resets error state on new execution attempts
🔤 String Utilities
Section titled “🔤 String Utilities”toKebabCase
Section titled “toKebabCase”Converts a string to kebab-case format (lowercase with hyphens).
toKebabCase Signature
Section titled “toKebabCase Signature”function toKebabCase(str: string): stringtoKebabCase Parameters
Section titled “toKebabCase Parameters”| Parameter | Type | Description |
|---|---|---|
str | string | The input string to convert |
toKebabCase Returns
Section titled “toKebabCase Returns”string- The kebab-cased string
toKebabCase Implementation Details
Section titled “toKebabCase Implementation Details”- Converts camelCase boundaries to hyphens (e.g.,
camelCase→camel-case) - Replaces spaces and underscores with hyphens
- Converts the entire string to lowercase
- Handles multiple consecutive separators correctly
toKebabCase Transformation Rules
Section titled “toKebabCase Transformation Rules”| Input Type | Example Input | Example Output |
|---|---|---|
| camelCase | camelCaseString | camel-case-string |
| PascalCase | PascalCaseString | pascal-case-string |
| snake_case | snake_case_string | snake-case-string |
| Spaces | Multiple Spaces | multiple-spaces |
| Mixed | Mixed_Case-String | mixed-case-string |
truncate
Section titled “truncate”Truncates a string to a specified maximum length and adds ellipsis if needed.
truncate Signature
Section titled “truncate Signature”function truncate(str: string, maxLength: number): stringtruncate Parameters
Section titled “truncate Parameters”| Parameter | Type | Description |
|---|---|---|
str | string | The input string to truncate |
maxLength | number | The maximum length including ellipsis |
truncate Returns
Section titled “truncate Returns”string- The truncated string with ellipsis if needed
truncate Implementation Details
Section titled “truncate Implementation Details”- Returns the original string if it’s shorter than or equal to
maxLength - Subtracts 3 characters from
maxLengthto account for ellipsis (...) - Always preserves the ellipsis length in the final result
- Does not break words (truncates at character level)
truncate Examples
Section titled “truncate Examples”| Input | Max Length | Output |
|---|---|---|
"Hello World" | 15 | "Hello World" |
"Hello World" | 8 | "Hello..." |
"Hi" | 10 | "Hi" |
slugify
Section titled “slugify”Converts a string to a URL-friendly slug format.
slugify Signature
Section titled “slugify Signature”function slugify(str: string): stringslugify Parameters
Section titled “slugify Parameters”| Parameter | Type | Description |
|---|---|---|
str | string | The input string to slugify |
slugify Returns
Section titled “slugify Returns”string- The URL-friendly slug
slugify Implementation Details
Section titled “slugify Implementation Details”- Converts to lowercase
- Removes leading and trailing whitespace
- Removes special characters (keeps only word characters, spaces, and hyphens)
- Replaces spaces, underscores, and multiple hyphens with single hyphens
- Removes leading and trailing hyphens
slugify Transformation Rules
Section titled “slugify Transformation Rules”| Input | Output | Rule Applied |
|---|---|---|
"Hello World!" | "hello-world" | Special chars removed, spaces to hyphens |
" JavaScript " | "javascript" | Trimmed and lowercased |
"API & REST" | "api-rest" | Special chars removed |
"Multi---Dash" | "multi-dash" | Multiple hyphens collapsed |
toTitleCase
Section titled “toTitleCase”Converts a string to title case (first letter of each word capitalized).
toTitleCase Signature
Section titled “toTitleCase Signature”function toTitleCase(str: string): stringtoTitleCase Parameters
Section titled “toTitleCase Parameters”| Parameter | Type | Description |
|---|---|---|
str | string | The input string to convert |
toTitleCase Returns
Section titled “toTitleCase Returns”string- The title-cased string
toTitleCase Implementation Details
Section titled “toTitleCase Implementation Details”- Converts the entire string to lowercase first
- Splits on spaces to identify words
- Capitalizes the first character of each word
- Preserves the spacing between words
- Does not handle complex title case rules (articles, prepositions, etc.)
toTitleCase Examples
Section titled “toTitleCase Examples”| Input | Output |
|---|---|
"hello world" | "Hello World" |
"JAVASCRIPT DEVELOPER" | "Javascript Developer" |
"mixed CaSe text" | "Mixed Case Text" |
🔍 Type Information
Section titled “🔍 Type Information”Hook Return Types
Section titled “Hook Return Types”// useDebouncetype UseDebouncedValue<T> = T
// useClickOutsidetype UseClickOutsideReturn<T extends HTMLElement> = React.RefObject<T | null>
// useAsynctype UseAsyncReturn<T extends (...args: any[]) => Promise<any>> = [ boolean, // loading Error | null, // error (...args: Parameters<T>) => Promise<ReturnType<T>> // execute]Utility Function Types
Section titled “Utility Function Types”// String utilitiestype StringTransformer = (str: string) => stringtype StringTruncator = (str: string, maxLength: number) => string
// All string utilities follow the StringTransformer pattern except truncatetype ToKebabCase = StringTransformertype Slugify = StringTransformertype ToTitleCase = StringTransformertype Truncate = StringTruncator🧪 Testing Types
Section titled “🧪 Testing Types”All utilities can be tested using standard TypeScript testing patterns:
import type { expectTypeOf } from 'vitest'import { toKebabCase, useDebounce } from '@sparkle/utils'
// String utilities are pure functions with predictable typesexpectTypeOf(toKebabCase).toEqualTypeOf<(str: string) => string>()
// Hooks maintain generic type safetyexpectTypeOf(useDebounce<string>).toEqualTypeOf<(value: string, delay: number) => string>()expectTypeOf(useDebounce<number>).toEqualTypeOf<(value: number, delay: number) => number>()📦 Package Exports
Section titled “📦 Package Exports”The @sparkle/utils package exports all utilities through named exports:
// All available exportsexport { slugify, toKebabCase, toTitleCase, truncate, useAsync, useClickOutside, useDebounce} from '@sparkle/utils'💡 Advanced Usage Patterns
Section titled “💡 Advanced Usage Patterns”Type-Safe Hook Composition
Section titled “Type-Safe Hook Composition”import { useAsync, useDebounce } from '@sparkle/utils'
// Compose hooks with full type safetyfunction useAsyncSearch( searchFn: (query: string) => Promise<SearchResult[]>, delay = 300) { const [query, setQuery] = useState('') const debouncedQuery = useDebounce(query, delay) const [loading, error, search] = useAsync(searchFn)
useEffect(() => { if (debouncedQuery) { search(debouncedQuery) } }, [debouncedQuery, search])
return { query, setQuery, loading, error }}String Utility Composition
Section titled “String Utility Composition”import { slugify, toKebabCase, truncate } from '@sparkle/utils'
// Create specialized utility functionsconst createUrlSlug = (title: string, maxLength = 50): string => truncate(slugify(title), maxLength)
const createCssClass = (component: string, variant?: string): string => variant ? `${toKebabCase(component)} ${toKebabCase(component)}--${toKebabCase(variant)}` : toKebabCase(component)