FluentUI Compat

Home > @cascadiacollections/fluentui-compat

fluentui-compat package

Classes

Class

Description

Async

Ultra-optimized Async utility class designed for high-performance React applications.

This class provides memory-efficient management of asynchronous operations with automatic cleanup on disposal. It's particularly useful for preventing memory leaks in React components where async operations might continue after component unmounting.

Key performance features: - ID pooling to reduce memory allocations - Batch timer operations to minimize system calls - Window reference caching to reduce DOM queries - Optimized state management in throttle/debounce functions - Development-time performance monitoring

EventGroup

Ultra-optimized EventGroup utility class for managing multiple event listeners.

This class provides centralized management of DOM event listeners with automatic cleanup on disposal. It's particularly useful in React components for preventing memory leaks from forgotten event listeners.

Key performance features: - Efficient event tracking using Map for O(1) lookups - Automatic cleanup of all listeners on dispose - Support for both function callbacks and object methods - Proper handling of event listener options - Type-safe event management with TypeScript - Window reference caching to reduce DOM queries

**Performance considerations**: - Uses Map for O(1) event lookup and removal - Minimal memory allocations per event - Efficient batch cleanup on dispose - No memory leaks from orphaned listeners

**React integration**: While this class can be used directly, consider using useOnEvent hook for simpler React integration that automatically handles cleanup via useEffect.

Functions

Function

Description

bundleIcon(FilledIcon, RegularIcon)

Creates an optimized bundled icon component that renders either a filled or regular icon based on the filled prop. The component is memoized for optimal render performance.

createMemoizer(getValue)

Creates a highly optimized memoizer for single-argument functions where the argument is an object or function. Uses WeakMap for automatic memory management.

This is ideal for functions that transform objects/functions and need automatic cleanup when the source objects are garbage collected.

getWindow(element)

Gets the window object associated with a DOM element. Returns undefined if the element is not in a browser environment.

This is a minimal implementation for use with the Async class, providing cross-environment compatibility.

memoizeFunction(fn, maxCacheSize, ignoreNullOrUndefinedResult)

Highly optimized memoization function that caches results based on argument identity. Provides configurable cache size limits and automatic memory management.

Key performance optimizations: - Uses WeakMap for automatic garbage collection of object arguments - Efficient primitive value caching with shared dictionary - Configurable cache size limits to prevent memory leaks - Global reset counter for bulk cache invalidation - Fast argument normalization

resetIdCounter(counter)

Reset the global ID counter. Useful for testing.

⚠️ **Warning**: This should only be used in tests. Calling this in production code can lead to duplicate IDs and accessibility issues.

resetMemoizations()

Reset all memoizations by incrementing the global reset counter. This is more efficient than clearing individual caches.

useAsync()

Hook to provide an Async instance that is automatically cleaned up on dismount.

This implementation is optimized for: - **Memory efficiency**: Uses useRef instead of useMemo to avoid closure overhead - **Render performance**: Minimizes effect overhead by consolidating development checks - **Immutability**: Ensures stable reference identity across all renders - **Type safety**: Leverages TypeScript strict mode and const assertions

useBoolean(initialState)

Hook to store a boolean value and generate callbacks for setting the value to true, false, or toggling it.

This hook is optimized for performance using idiomatic React patterns: - The identity of the callbacks will always stay the same across renders - Uses useMemo with empty dependencies for stable callback object - Avoids unnecessary function closures and object recreations - Provides stable referential identity for the callbacks object

useConst(initialValue)

Hook to initialize and return a constant value with stable identity.

Unlike React.useMemo, this hook guarantees: - The initializer function is called exactly once - The returned value identity never changes - No re-computation on dependency changes

This is equivalent to setting a private member in a class constructor.

useEventCallback(fn)

Hook to create a stable event handler that always calls the latest version of the callback.

This hook solves the problem where event handlers need access to the latest props/state without causing unnecessary re-renders or re-registrations of event listeners.

**Key Features**: - **Stable reference**: The returned callback has a stable identity that never changes - **Fresh values**: Always executes the latest version of the callback with current props/state - **Performance optimized**: Prevents re-renders in child components that depend on the callback - **Type safe**: Full TypeScript support with generic argument and return types - **React 19 compatible**: Uses useLayoutEffect for synchronous updates

**When to use**: - Event handlers that depend on frequently changing props/state - Callbacks passed to memoized child components to prevent unnecessary re-renders - Event listeners attached to window, document, or long-lived DOM elements - Callbacks in useEffect dependencies that shouldn't trigger the effect on every change

**Implementation Details**: - Uses useLayoutEffect to ensure callback ref updates synchronously before paint - Leverages useConst for a truly stable wrapper function that never changes - Throws error if called during render to enforce proper React patterns - Minimal overhead with no additional dependencies or complex state management

useForceUpdate()

Hook to force update a function component by triggering a re-render.

**⚠️ Performance Warning**: This hook will intentionally cause re-renders and should be used sparingly with clear intent. Overuse may introduce performance issues and long-running tasks. Consider using React's built-in state management patterns (useState, useReducer) or memoization strategies (useMemo, useCallback) before resorting to force updates.

**🔧 Development Tools**: In development builds, this hook provides enhanced debugging features: - **Performance monitoring**: Tracks call frequency and warns about excessive usage - **Rapid call detection**: Alerts when multiple calls occur within a single frame (16ms) - **DevTools integration**: Displays call count in React DevTools for debugging - **Profiler marks**: Creates performance markers for React Profiler analysis - **Cleanup warnings**: Detects components with short lifetimes but many force updates

This implementation uses useReducer for optimal performance: - **Memory efficient**: No additional closures or function allocations - **Stable reference**: The returned function identity never changes - **Minimal overhead**: Uses React's optimized reducer dispatch mechanism - **No dependencies**: Eliminates the need for additional custom hooks

useId(prefix)

Hook to generate a stable unique ID for the component instance.

This hook provides a consistent way to generate IDs for accessibility attributes and form elements. The generated ID is: - **Stable**: Never changes across renders for the same component instance - **Unique**: Guaranteed unique across all components using this hook - **Predictable**: Uses an optional prefix for easier debugging - **SSR-compatible**: Works correctly with server-side rendering

**Use cases**: - Linking form labels to inputs via htmlFor and id - ARIA attributes like aria-labelledby, aria-describedby - Creating unique identifiers for DOM elements - Managing focus and accessibility relationships

**React 18+ Alternative**: For React 18+, consider using the built-in useId() hook. This implementation is provided for React 16 and 17 compatibility.

useMergedRefs(refs)

Hook to merge multiple refs into a single ref callback.

When working with React refs, you often need to handle multiple refs on the same element: - Your own ref for component logic - A forwarded ref from a parent component - Refs from third-party libraries

This hook merges all refs into a single callback ref that updates all of them.

**Features**: - **Flexible input**: Accepts any combination of callback refs, ref objects, and null/undefined - **Type safe**: Full TypeScript support with proper type inference - **Performance optimized**: Memoizes the callback to prevent unnecessary re-renders - **Cleanup safe**: Properly cleans up all refs when the element unmounts - **SSR compatible**: Works correctly with server-side rendering

useOnEvent(target, eventName, handler, options)

Hook to attach event listeners to window or document with automatic cleanup.

This hook provides a declarative way to manage event listeners that: - **Automatically cleans up**: Removes listeners on unmount or when dependencies change - **Type safe**: Full TypeScript support for event types - **Performance optimized**: Uses stable callbacks to prevent re-registration - **SSR safe**: Handles server-side rendering gracefully - **Flexible target**: Supports window, document, or any event target

**Common use cases**: - Window resize, scroll events - Document click/keydown for global interactions - Custom events on event targets - Keyboard shortcuts - Outside click detection

useOnEvent(target, eventName, handler, options)

useOnEvent(target, eventName, handler, options)

useOnEvent(target, eventName, handler, options)

usePrevious(value)

Hook to track and return the previous value of a prop or state.

This hook captures and returns the value from the previous render, which is useful for: - **Comparison logic**: Detecting when a value has changed - **Animation triggers**: Starting animations when values change - **Effect optimization**: Avoiding unnecessary effects when values haven't changed - **Debugging**: Tracking value changes over time

**Implementation Details**: - Uses useEffect to update the previous value after render - On first render, returns undefined since there's no previous value - Works with any type including primitives, objects, and functions - Does not deep-compare objects - only tracks reference changes

useSetTimeout()

Hook to provide performance optimized timeout management with automatic cleanup.

This hook provides a wrapper around setTimeout and clearTimeout that: - Automatically cleans up all active timeouts when the component unmounts - Uses Set for O(1) add/remove operations instead of Record for better performance - Auto-removes timeouts from tracking when they execute naturally - Returns a memoized object to prevent unnecessary re-renders

Interfaces

Interface

Description

BundledIconProps

FluentThemeConsumerProps

ICancelable

Interface for cancelable functions returned by debounce. Provides additional control over the debounced function execution.

IEventTarget

Interface for event targets that support addEventListener and removeEventListener.

IUseBooleanCallbacks

Updater callbacks returned by useBoolean.

SmartFluentProviderProps

Variables

Variable

Description

FluentThemeConsumer

Lightweight alternative to FluentProvider for simple theme overrides. Use this instead of nesting FluentProvider when you only need theme changes.

This component provides a minimal way to override theme tokens without the overhead of a full FluentProvider, making it ideal for performance-critical scenarios where only theme changes are needed.

SmartFluentProvider

A smart FluentProvider that automatically detects when it would be redundant and either warns in development or skips creating a provider in production.

This helps prevent unnecessary provider nesting while maintaining the same API as the standard FluentProvider.

useIsomorphicLayoutEffect

Hook that uses useLayoutEffect on the client and useEffect on the server.

React throws a warning when using useLayoutEffect during server-side rendering because layout effects don't run on the server. This hook provides a drop-in replacement that: - Uses useLayoutEffect in the browser for synchronous DOM updates - Uses useEffect on the server to avoid SSR warnings - Maintains the same API as useLayoutEffect

**When to use**: - Measuring DOM elements and updating state before paint - Synchronizing with external systems before browser paint - Reading layout information and causing a synchronous re-render - Any case where you need useLayoutEffect but also support SSR

**When NOT to use**: - Most effects should use regular useEffect instead - Only use this when timing relative to browser paint matters - If you don't need SSR support, use useLayoutEffect directly

Type Aliases

Type Alias

Description

EventListenerOptions_2

Event listener options that can be passed to addEventListener.

TimeoutId

The timeout ID type that works across different environments

UseSetTimeoutReturnType

  • Edit this page
In this article
Back to top FluentUI React complimentary components and utilities focused on render performance