Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

よくあるインクリメンタルサーチやオートコンプリートとかで、入力されたクエリに応じてリクエストを飛ばす時に、お手軽に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)} />
  )
}
seya
最近の趣味はGraphQLとFigmaです。
https://note.mu/seyanote
linc-well
Linc'well(リンクウェル)は2018年創業のヘルスケアスタートアップです。我々は、医療のIT化を通じて、人々と社会の健康に貢献します。
https://www.linc-well.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした