use-debounced-effect

Runs an effect debounced when its dependencies change

Usage

use-debounced-effect works like useEffect, but the effect runs only after its dependencies stop changing for the given delay. Use it for side effects that depend on rapidly changing values, for example fetching search results:

Effect runs: 0

Last searched: –

import { useState } from 'react';
import { Badge, Group, Stack, Text, TextInput } from '@mantine/core';
import { useDebouncedEffect } from '@mantine/hooks';

function Demo() {
  const [query, setQuery] = useState('');
  const [runs, setRuns] = useState(0);
  const [lastQuery, setLastQuery] = useState('');

  useDebouncedEffect(
    () => {
      setRuns((current) => current + 1);
      setLastQuery(query);
    },
    [query],
    500
  );

  return (
    <Stack>
      <TextInput
        label="Type quickly – the effect runs 500ms after you stop"
        placeholder="Search..."
        value={query}
        onChange={(event) => setQuery(event.currentTarget.value)}
      />
      <Group>
        <Badge>Effect runs: {runs}</Badge>
        <Text size="sm">Last searched: {lastQuery || '–'}</Text>
      </Group>
    </Stack>
  );
}

Difference from useEffect

The effect does not run immediately on mount, it runs delay milliseconds after the mount and after each dependencies change. Set the leading option to run it immediately.

The effect may return a cleanup function. It is called before the next run and on unmount.

Options

The third argument is either a delay number or an options object:

import { useDebouncedEffect } from '@mantine/hooks';

// Delay shorthand
useDebouncedEffect(() => fetchResults(query), [query], 300);

// Options object
useDebouncedEffect(() => fetchResults(query), [query], {
  delay: 300,
  // Run the effect immediately on the first change, then ignore changes within the delay window
  leading: true,
  // Guarantee that the effect runs at least once every 1000ms while the deps keep changing
  maxWait: 1000,
});

Definition

interface UseDebouncedEffectOptions {
  delay: number;
  leading?: boolean;
  maxWait?: number;
}

function useDebouncedEffect(
  effect: React.EffectCallback,
  deps: React.DependencyList,
  options: number | UseDebouncedEffectOptions
): void;

Exported types

UseDebouncedEffectOptions type is exported from the @mantine/hooks package, you can import it in your application:

import type { UseDebouncedEffectOptions } from '@mantine/hooks';