Skip to content

Utility Reference

Complete TypeScript API reference for all utilities provided by @sparkle/utils.

Debounces a rapidly changing value to limit how often it updates.

function useDebounce<T>(value: T, delay: number): T
  • T - The type of the value being debounced
ParameterTypeDescription
valueTThe value to debounce
delaynumberThe delay in milliseconds
  • T - The debounced value
  • Uses useState and useEffect internally
  • 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

Detects clicks outside of a specified element and executes a callback function.

function useClickOutside<T extends HTMLElement>(
handler: () => void
): React.RefObject<T | null>
  • T extends HTMLElement - The type of HTML element to monitor (defaults to HTMLElement)
ParameterTypeDescription
handler() => voidCallback function to execute when clicking outside
  • React.RefObject<T \| null> - A ref object to attach to the target element
  • Listens for both mousedown and touchstart events
  • Automatically removes event listeners on cleanup
  • Uses useRef and useEffect for efficient event management
  • Checks if the clicked element is contained within the ref element

Manages the state of asynchronous operations with loading, error, and execution tracking.

function useAsync<T extends (...args: any[]) => Promise<any>>(
asyncFn: T
): [boolean, Error | null, (...args: Parameters<T>) => Promise<ReturnType<T>>]
  • T extends (...args: any[]) => Promise<any> - The type of the async function
ParameterTypeDescription
asyncFnTThe async function to manage

Tuple containing:

  1. boolean - Loading state (true when operation is in progress)
  2. Error \| null - Error state (null if no error occurred)
  3. (...args: Parameters<T>) => Promise<ReturnType<T>> - Memoized execution function
  • Uses useState for loading and error state management
  • Uses useCallback to 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

Converts a string to kebab-case format (lowercase with hyphens).

function toKebabCase(str: string): string
ParameterTypeDescription
strstringThe input string to convert
  • string - The kebab-cased string
  • Converts camelCase boundaries to hyphens (e.g., camelCasecamel-case)
  • Replaces spaces and underscores with hyphens
  • Converts the entire string to lowercase
  • Handles multiple consecutive separators correctly
Input TypeExample InputExample Output
camelCasecamelCaseStringcamel-case-string
PascalCasePascalCaseStringpascal-case-string
snake_casesnake_case_stringsnake-case-string
SpacesMultiple Spacesmultiple-spaces
MixedMixed_Case-Stringmixed-case-string

Truncates a string to a specified maximum length and adds ellipsis if needed.

function truncate(str: string, maxLength: number): string
ParameterTypeDescription
strstringThe input string to truncate
maxLengthnumberThe maximum length including ellipsis
  • string - The truncated string with ellipsis if needed
  • Returns the original string if it’s shorter than or equal to maxLength
  • Subtracts 3 characters from maxLength to account for ellipsis (...)
  • Always preserves the ellipsis length in the final result
  • Does not break words (truncates at character level)
InputMax LengthOutput
"Hello World"15"Hello World"
"Hello World"8"Hello..."
"Hi"10"Hi"

Converts a string to a URL-friendly slug format.

function slugify(str: string): string
ParameterTypeDescription
strstringThe input string to slugify
  • string - The URL-friendly slug
  • 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
InputOutputRule 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

Converts a string to title case (first letter of each word capitalized).

function toTitleCase(str: string): string
ParameterTypeDescription
strstringThe input string to convert
  • string - The title-cased string
  • 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.)
InputOutput
"hello world""Hello World"
"JAVASCRIPT DEVELOPER""Javascript Developer"
"mixed CaSe text""Mixed Case Text"
// useDebounce
type UseDebouncedValue<T> = T
// useClickOutside
type UseClickOutsideReturn<T extends HTMLElement> = React.RefObject<T | null>
// useAsync
type UseAsyncReturn<T extends (...args: any[]) => Promise<any>> = [
boolean, // loading
Error | null, // error
(...args: Parameters<T>) => Promise<ReturnType<T>> // execute
]
// String utilities
type StringTransformer = (str: string) => string
type StringTruncator = (str: string, maxLength: number) => string
// All string utilities follow the StringTransformer pattern except truncate
type ToKebabCase = StringTransformer
type Slugify = StringTransformer
type ToTitleCase = StringTransformer
type Truncate = StringTruncator

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 types
expectTypeOf(toKebabCase).toEqualTypeOf<(str: string) => string>()
// Hooks maintain generic type safety
expectTypeOf(useDebounce<string>).toEqualTypeOf<(value: string, delay: number) => string>()
expectTypeOf(useDebounce<number>).toEqualTypeOf<(value: number, delay: number) => number>()

The @sparkle/utils package exports all utilities through named exports:

// All available exports
export {
slugify,
toKebabCase,
toTitleCase,
truncate,
useAsync,
useClickOutside,
useDebounce
} from '@sparkle/utils'
import { useAsync, useDebounce } from '@sparkle/utils'
// Compose hooks with full type safety
function 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 }
}
import { slugify, toKebabCase, truncate } from '@sparkle/utils'
// Create specialized utility functions
const 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)