useId function

String useId({
  1. String prefix = 'jh',
})

Returns an HTML id that is stable across rebuilds and hot reload.

For island hydration, use a HookIdScope inside the client boundary. Without a scope, IDs use the complete element path and only match between server and client when those complete trees match. The generated format is opaque.

Implementation

String useId({String prefix = 'jh'}) {
  if (prefix.isEmpty) {
    throw ArgumentError.value(prefix, 'prefix', 'must not be empty');
  }
  final element = HookElement.currentHookElement;
  if (element == null) {
    throw StateError('useId() can only be called while a hook component is building.');
  }
  final scope = element.dependOnInheritedComponentOfExactType<HookIdScope>();
  if (scope != null && scope.seed.isEmpty) {
    throw ArgumentError.value(scope.seed, 'seed', 'must not be empty');
  }
  final scopeElement = element.getElementForInheritedComponentOfExactType<HookIdScope>() as _HookIdScopeElement?;
  return use(_IdHook(prefix, element._currentHookIndex, scope?.seed, scopeElement));
}