FluentUI Compat

Home > @cascadiacollections/fluentui-compat > useConst

useConst() function

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.

Signature:

export declare function useConst<T>(initialValue: T | (() => T)): T;

Parameters

Parameter

Type

Description

initialValue

T | (() => T)

The initial value or a function that returns the initial value. Only the value/function passed on the first render is used.

**Returns:**

T

The constant value. The identity of this value will always be the same.

Example 1

// Initialize with a value
const constantValue = useConst(42);

// Initialize with a function (called only once)
const expensiveObject = useConst(() => ({
  data: performExpensiveComputation(),
  timestamp: Date.now()
}));

// Works correctly with falsy values
const undefinedValue = useConst(() => undefined);
const nullValue = useConst(null);
const falseValue = useConst(false);

Example 2

// Common use cases
function MyComponent() {
  // Create stable RegExp instance
  const emailRegex = useConst(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/);

  // Create stable configuration object
  const config = useConst(() => ({
    apiUrl: process.env.REACT_APP_API_URL,
    timeout: 5000
  }));

  // Create stable event handler
  const handleClick = useConst(() => () => {
    console.log('Button clicked');
  });

  return <button onClick={handleClick}>Click me</button>;
}
  • Edit this page
In this article
Back to top FluentUI React complimentary components and utilities focused on render performance