Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
20
Help us understand the problem. What is going on with this article?
@seya

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)} />
  )
}
20
Help us understand the problem. What is going on with this article?
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
seya
最近の趣味はGraphQLとFigmaです。
linc-well
Linc'well(リンクウェル)は2018年創業のヘルスケアスタートアップです。我々は、医療のIT化を通じて、人々と社会の健康に貢献します。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
20
Help us understand the problem. What is going on with this article?