useStore<T> method

StoreHook<T> useStore<T>(
  1. Store<T> store
)

Create a store hook for global state

Implementation

StoreHook<T> useStore<T>(Store<T> store) {
  if (_hookIndex >= _hooks.length) {
    // Create new hook with update protection and component tracking
    final hook = StoreHook<T>(store, () {
      // Only schedule update if component is mounted and not already updating
      if (_isMounted && !_isUpdating) {
        _isUpdating = true;
        scheduleUpdate();
        // Reset updating flag after microtask to prevent rapid successive updates
        Future.microtask(() {
          _isUpdating = false;
        });
      }
    }, instanceId, typeName);
    _hooks.add(hook);
  }

  // Get the hook (either existing or newly created)
  final hook = _hooks[_hookIndex] as StoreHook<T>;

  // Verify this hook is for the same store to prevent mismatches
  if (hook.store != store) {
    if (kDebugMode) {
      print('Warning: Store hook mismatch detected, disposing old hook and creating new one');
    }
    // Dispose the old hook and create a new one
    hook.dispose();
    final newHook = StoreHook<T>(store, () {
      if (_isMounted && !_isUpdating) {
        _isUpdating = true;
        scheduleUpdate();
        Future.microtask(() {
          _isUpdating = false;
        });
      }
    }, instanceId, typeName);
    _hooks[_hookIndex] = newHook;
    _hookIndex++;
    return newHook;
  }

  _hookIndex++;
  return hook;
}