onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to debounce text input in React #953

Open onmyway133 opened 1 year ago

onmyway133 commented 1 year ago

Use debounce from lodash and useCallback to memoize debounce function

import React, { useCallback } from "react"
import debounce from "lodash/debounce"

const SearchField = (props: Props) => {
    const callback = useCallback(
        debounce((value: string) => {
            props.setFilter({
                ...props.filter,
                searchText: value,
            })
        }),
        []
    )

    const handleChange = (value: string) => {
        callback(value)
    }

    return (
        <div>
            <Input
                value={props.filter.searchText}
                placeholder="Search"
                variant="bordered"
                onValueChange={handleChange}
            />
        </div>
    )
}