Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

1.2 KB
Raw Blame
import type { Selector } from '@reduxjs/toolkit';
import type { RootState } from 'app/store/store';
import { useAppStore } from 'app/store/storeHooks';
import { useEffect, useState } from 'react';

/**
 * A hook that returns a debounced value from the app state.
 *
 * @param selector The redux selector
 * @param debounceMs The debounce time in milliseconds
 * @returns The debounced value
 */
export const useDebouncedAppSelector = <T>(selector: Selector<RootState, T>, debounceMs: number = 300) => {
  const store = useAppStore();
  const [value, setValue] = useState<T>(() => selector(store.getState()));

  useEffect(() => {
    let prevValue = selector(store.getState());
    let timeout: number | null = null;

    const unsubscribe = store.subscribe(() => {
      const value = selector(store.getState());
      if (value !== prevValue) {
        if (timeout !== null) {
          window.clearTimeout(timeout);
        }
        timeout = window.setTimeout(() => {
          setValue(value);
          prevValue = value;
        }, debounceMs);
      }
    });

    return () => {
      unsubscribe();
      if (timeout !== null) {
        window.clearTimeout(timeout);
      }
    };
  }, [debounceMs, selector, store]);

  return value;
};