useDebounce

The useDebounce hook takes a value, and returns the same value after a delay. If the input value changes, the delay will reset. This is useful to delay expensive operations, like applying a database filter, when they are triggered as a direct result of user input. The default delay is 300ms.

A common usage for this is to have a search field that automatically filters a data object. To avoid having a network call triggered by every keypress, the input value is passed through the debounce hook.

import { List, ListItem, ListItemText, TextField } from "@olenbetong/appframe-mui";
import { useDebounce, useData } from "@olenbetong/appframe-react";

function MySearchComponent() {
  let [input, setInput] = useState("");
  let query = useDebounce(input);
  let results = useData(
    dsMyDataObject,
    {
      filter: query
        ? query
            .split(/\s+/) // split by whitespace
            .map((word) => `[SearchColumn] LIKE '%${word}%'`)
            .join(" AND ")
        : false,
    }
  );

  return (
    <>
      <TextField
        label="search"
        value={input}
        onChange={(evt) => setInput(evt.target.value)}
      />
      <List>
        {results.map((result) => (
          <ListItem key={result.PrimKey}>
            <ListItemText
              primary={result.Title}
              secondary={result.Description}
            />
          </ListItem>
        ))}
      </List>
    </>
  );
}

API

Last updated

Was this helpful?