useDebounce Custom Hook

May 12, 2023

React Hooks

useDebounce Custom Hook

Thuta Sann

Thuta Sann

In this section, useDebounce Custom Hook will be written.


Share This Snippet To :

Debouncing is a programming pattern or a technique
to restrict the calling of a time-consuming function frequently,
by delaying the execution of the function until a specified time
to avoid unnecessary CPU cycles,
import { useState } from 'react' export const useDebounce = (timeout = 500) => { const [timer, setTimer] = useState(0) const debounce = (fn: () => void) => { if (timer) clearTimeout(timer) const newTimer: any = setTimeout(() => fn(), timeout) setTimer(newTimer) } return { debounce } } // Usage const TimeIntervalPicker = (value: any) => { const { debounce } = useDebounce() const scrollIntoView = (time = value) => { debounce(() => { document.getElementById(time?.format('hh:mm A'))?.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'nearest', }) }) } }

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?