How to use use-debounce - 10 common examples

To help you get started, we’ve selected a few use-debounce examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github christiandavid / gatsby-theme-byfolio / @christiandavid / gatsby-theme-byfolio / src / components / hooks / useWnResize.js View on Github external
function useWnResize(ref = false, delay = 500) {
  const [windowSize, setWindowSize] = useState(null)

  const getSize = useCallback(() => {
    // Setting state to the updated matches
    setWindowSize({
      width: ref === false ? window.innerWidth : ref.current.offsetWidth,
      height: ref === false ? window.innerHeight : ref.current.offsetHeight,
    })
  }, [ref])

  const [resizeHandler] = useDebouncedCallback(() => {
    getSize()
  }, delay)

  useEffect(() => {
    if (!isSSR) {
      // Add listener
      window.addEventListener("resize", resizeHandler)
      getSize()
    }

    return () => {
      // Remove listener
      !isSSR && window.removeEventListener("resize", resizeHandler)
    }
  }, [resizeHandler, ref, getSize])
github getredash / redash / client / app / lib / hooks / useSearchResults.js View on Github external
export default function useSearchResults(fetch, { initialResults = null, debounceTimeout = 200 } = {}) {
  const [result, setResult] = useState(initialResults);
  const [isLoading, setIsLoading] = useState(false);
  const currentSearchTerm = useRef(null);
  const isDestroyed = useRef(false);

  const [doSearch] = useDebouncedCallback(searchTerm => {
    setIsLoading(true);
    currentSearchTerm.current = searchTerm;
    fetch(searchTerm)
      .catch(() => null)
      .then(data => {
        if (searchTerm === currentSearchTerm.current && !isDestroyed.current) {
          setResult(data);
          setIsLoading(false);
        }
      });
  }, debounceTimeout);

  useEffect(
    () =>
      // ignore all requests after component destruction
      () => {
github christiandavid / gatsby-theme-byfolio / @christiandavid / gatsby-theme-byfolio / src / components / hooks / useMQResize.js View on Github external
function useMQResize(queries) {
  const [queryMatch, setQueryMatch] = useState(null)
  const keys = useRef(Object.keys(queries))

  const handleQuery = useCallback(() => {
    const updatedMatches = keys.current.reduce((acum, media) => {
      acum[media] = !!window.matchMedia(queries[media]).matches
      return acum
    }, {})

    // Setting state to the updated matches
    setQueryMatch(updatedMatches)
  }, [queries])

  const [resizeHandler] = useDebouncedCallback(
    () => {
      handleQuery()
    },
    // Delay
    500
  )

  useEffect(() => {
    if (!isSSR && window.matchMedia) {
      // Add listener
      window.addEventListener("resize", resizeHandler)
      handleQuery()
    }

    return () => {
      // Remove listener
github pubpub / pubpub / client / components / FormattingBarNew / controls / ControlsEquation.js View on Github external
const ControlsEquation = (props) => {
	const { editorChangeObject, onPendingChanges, onClose } = props;
	const { changeNode, selectedNode, updateNode } = editorChangeObject;
	const {
		commitChanges,
		revertChanges,
		hasPendingChanges,
		updateAttrs,
		pendingAttrs,
	} = useCommitAttrs(selectedNode.attrs, updateNode, onPendingChanges);
	const { value, html } = pendingAttrs;
	const [debouncedValue] = useDebounce(value, 250);
	const hasMountedRef = useRef(false);
	const isBlock = selectedNode.type.name === 'block_equation';

	useEffect(() => {
		// Avoid an initial call to the server's LaTeX renderer on mount
		// We shouldn't need this anyway -- but moreover, it will sometimes produce HTML that is
		// insubstantially different from that given in our Prosemirror schema definitions, making
		// it appear as though there is a user-driven change to the node that needs to be committed
		// or reverted.
		if (!hasMountedRef.current) {
			hasMountedRef.current = true;
			return;
		}
		renderLatexString(debouncedValue, false, (nextHtml) => {
			updateAttrs({ html: nextHtml });
		});
github woocommerce / woocommerce-gutenberg-products-block / assets / js / base / hooks / use-collection-data.js View on Github external
useEffect( () => {
		if (
			calculatePriceRangeQueryState !== currentQueryPrices &&
			currentQueryPrices !== undefined
		) {
			setCalculatePriceRangeQueryState( currentQueryPrices );
		}
	}, [
		currentQueryPrices,
		setCalculatePriceRangeQueryState,
		calculatePriceRangeQueryState,
	] );

	// Defer the select query so all collection-data query vars can be gathered.
	const [ shouldSelect, setShouldSelect ] = useState( false );
	const [ debouncedShouldSelect ] = useDebounce( shouldSelect, 200 );

	if ( ! shouldSelect ) {
		setShouldSelect( true );
	}

	const collectionDataQueryVars = useMemo( () => {
		return buildCollectionDataQuery( collectionDataQueryState );
	}, [ collectionDataQueryState ] );

	return useCollection( {
		namespace: '/wc/store',
		resourceName: 'products/collection-data',
		query: {
			...queryState,
			page: undefined,
			per_page: undefined,
github Automattic / wp-calypso / client / landing / gutenboarding / components / domain-picker / list.tsx View on Github external
const DomainPicker: FunctionComponent< Props > = ( {
	defaultQuery,
	onDomainSelect,
	queryParameters,
} ) => {
	const label = NO__( 'Search for a domain' );

	const [ domainSearch, setDomainSearch ] = useState( '' );

	const [ search ] = useDebounce( domainSearch.trim() || defaultQuery || '', selectorDebounce );
	const suggestions = useSelect(
		select => {
			if ( search ) {
				return select( DOMAIN_SUGGESTIONS_STORE ).getDomainSuggestions( search, {
					include_wordpressdotcom: true,
					include_dotblogsubdomain: true,
					quantity: 4,
					...queryParameters,
				} );
			}
		},
		[ search, queryParameters ]
	);

	const handleHasDomain = () => {
		// eslint-disable-next-line no-console
github pubpub / pubpub / client / components / FormattingBarNew / controls / ControlsLink.js View on Github external
const ControlsLink = (props) => {
	const {
		editorChangeObject: { activeLink },
		onClose,
	} = props;

	const [href, setHref] = useState(activeLink.attrs.href);
	const [debouncedHref] = useDebounce(href, 250);

	// eslint-disable-next-line react-hooks/exhaustive-deps
	useEffect(() => activeLink.updateAttrs({ href: debouncedHref }), [debouncedHref]);

	const handleKeyPress = (evt) => {
		if (evt.key === 'Enter') {
			activeLink.updateAttrs({ href: href });
			onClose();
		}
	};

	return (
		<div>
			</div>
github php4dev / heroku-wordpress / wp-content / plugins / woocommerce / packages / woocommerce-blocks / assets / js / base / hooks / use-collection-data.js View on Github external
useEffect( () => {
		if (
			calculatePriceRangeQueryState !== currentQueryPrices &&
			currentQueryPrices !== undefined
		) {
			setCalculatePriceRangeQueryState( currentQueryPrices );
		}
	}, [
		currentQueryPrices,
		setCalculatePriceRangeQueryState,
		calculatePriceRangeQueryState,
	] );

	// Defer the select query so all collection-data query vars can be gathered.
	const [ shouldSelect, setShouldSelect ] = useState( false );
	const [ debouncedShouldSelect ] = useDebounce( shouldSelect, 200 );

	if ( ! shouldSelect ) {
		setShouldSelect( true );
	}

	const collectionDataQueryVars = useMemo( () => {
		return buildCollectionDataQuery( collectionDataQueryState );
	}, [ collectionDataQueryState ] );

	return useCollection( {
		namespace: '/wc/store',
		resourceName: 'products/collection-data',
		query: {
			...queryState,
			page: undefined,
			per_page: undefined,
github sillsdev / appbuilder-portal / source / SIL.AppBuilder.Portal.Frontend / src / ui / components / sidebar / org-switcher / with-data.tsx View on Github external
setCurrentOrganizationId,
    organizationsAvailableToUser: organizations,
  } = useCurrentOrganization();

  const [searchResults, setResults] = useState(organizations);

  const selectOrganization = (id) => () => {
    setCurrentOrganizationId(id);
    toggle();
  };

  // TODO: clean this up once
  //       https://github.com/orbitjs/orbit/pull/525
  //       is merged, where we'll be able to retrieve the query result
  //       without local filtering. (so we can skip the cache query step)
  const performSearch = useDebouncedCallback(
    async () => {
      const filters = [{ attribute: 'name', value: `like:${searchTerm}` }];

      if (!isSuperAdmin) {
        filters.push({ attribute: 'scope-to-current-user', value: 'isnull:' });
      }

      await dataStore.query((q) => q.findRecords(ORGANIZATION).filter(filters), defaultOptions());

      const records = await dataStore.cache.query((q) => q.findRecords(ORGANIZATION));
      // TODO: MAY need to do a local filter on organizations that the current user owns
      const filtered = records.filter((record) => {
        const { name } = attributesFor(record);
        if (!name) {
          return false;
        }
github sillsdev / appbuilder-portal / source / SIL.AppBuilder.Portal.Frontend / src / ui / components / inputs / auto-saving-input / index.tsx View on Github external
export default function AutoSavingInput({ value, onChange, InputElement, timeout }: IProps) {
  const Input = InputElement || Form.TextArea;
  const [localValue, setLocalValue] = useState(value);
  const save = useDebouncedCallback((newValue) =&gt; onChange(newValue), timeout, []);

  const onInputChange = (e: React.KeyboardEvent) =&gt; {
    const newValue = e.currentTarget.value;

    if (localValue === newValue) {
      return;
    }

    setLocalValue(newValue);
    save(newValue);
  };

  const onFormSubmit = (e: React.FormEvent) =&gt; {
    e.preventDefault();

    onChange(localValue);

use-debounce

Debounce hook for react

MIT
Latest version published 4 months ago

Package Health Score

85 / 100
Full package analysis