31
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React hooks でインクリメンタルサーチやオートコンプリートでのdebounceをお手軽にする

Posted at

よくあるインクリメンタルサーチやオートコンプリートとかで、入力されたクエリに応じてリクエストを飛ばす時に、お手軽にdebounceするためのhooks。

import * as React from 'react';

// 自分で定義するのがめんどい人は react-use の useDebounce 使うとよろし
function useDebounce(fn: () => any, ms: number = 0, args: any[] = []) {
  React.useEffect(() => {
    const handle = setTimeout(fn.bind(null, args), ms);

    return () => {
      clearTimeout(handle);
    };
  }, args);
};

export default function useDebouncedQuery(onChange: (query: string) => void) {
  const [searchQuery, setSearchQuery] = React.useState('');

  useDebounce(
    () => {
      onChange(searchQuery);
    },
    400,
    [searchQuery]
  );

  const clearQuery = React.useCallback(() => {
    setSearchQuery('');
  }, []);

  return { searchQuery, setSearchQuery, clearQuery };
}

使う側例

function Hoge() {
  const loadSuggestions = (query: string) => { ... }

  const { searchQuery, setSearchQuery } = useDebouncedQuery(loadSuggestions);

  return (
    <Input value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
  )
}
31
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?