React Throttle-Debounce usage

Date: 2021-07-12

From: https://aldaviva.com/portfolio.html#ratelimiting

/* eslint-disable react-hooks/exhaustive-deps */
import { Form, Input } from "antd";
import Search from "antd/lib/input/Search";
import React, { ChangeEvent, useCallback, useEffect, useRef, useState } from "react";
import { debounce, throttle } from "throttle-debounce";
import { translate } from "../../../domain/wiring/AppDomain";

export function SearchInput(props: { searchText: string; onSearch: (searchText: string) => any }) {
    const { searchText, onSearch } = props;

    const [typedSearchText, setTypedSearchText] = useState<string>(searchText);

    const doSearch = (value: string) => {
        setTypedSearchText(value);
        onSearch(value);
    };

    const throttledSearch = useCallback(throttle(4000, doSearch), []);
    const debouncedSearch = useCallback(debounce(2000, doSearch), []);

    const updateSearchText = (e: ChangeEvent<HTMLInputElement>) => {
        setTypedSearchText(e.target.value);
        debouncedSearch(e.target.value);
    };

    const inputRef = useRef<Input>() as React.MutableRefObject<Input>;

    useEffect(() => {
        if (inputRef?.current) { setTimeout(() => inputRef.current.input.focus(), 100); }
    }, []);

    return <Form name="basic" initialValues={{ remember: true }}>
        <Form.Item
            label={translate("general.search")}
            name="search">
            <Search ref={inputRef} placeholder={translate("general.search")} value={typedSearchText} onChange={updateSearchText} allowClear onSearch={throttledSearch} enterButton autoFocus />
        </Form.Item>
    </Form>;
}
51580cookie-checkReact Throttle-Debounce usage