DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 13

Today's task is to implement a useDebounce hook for a frequently changing value, such as a text input.

Debouncing means to discard operations that occur too close together within a specific time interval and consolidate them into a single invocation. An example will be when a user is typing in a text field, no other action (such as filtering, autocomplete, etc) should be taken until the user pauses.

The boilerplate code:

export function useDebounce<T>(value: T, delay: number): T { // your code here } // if you want to try your code on the right panel // remember to export App() component like below // export function App() { // return <div>your app</div> // } 
Enter fullscreen mode Exit fullscreen mode

The first will be to create the variables to set the debounced values.

const [debouncedValue, setDebouncedValue] = useState(value) 
Enter fullscreen mode Exit fullscreen mode

The next step is to create a function that sets up a timer that waits for a given delay, after which the debounced value is updated to match the latest text value.

useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value) }, delay) return () => { clearTimeout(handler) } }, [value, delay]) return debouncedValue 
Enter fullscreen mode Exit fullscreen mode

If the value of the text is changed before the delay period ends, the clearTimeout resets the timer to prevent updating too often.

The final code with an example of how the debounced value is displayed:

import React, { useState, useEffect } from "react" export function useDebounce<T>(value: T, delay: number): T { // your code here const [debouncedValue, setDebouncedValue] = useState(value) useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value) }, delay) return () => { clearTimeout(handler) } }, [value, delay]) return debouncedValue; } // if you want to try your code on the right panel // remember to export App() component like below export function App() { const[text, setText] = useState("") const debouncedText = useDebounce(text, 500) return ( <div> <input value={text} onChange={(e) => setText(e.target.value)} /> <p>Immediate value: {text}</p> <p>Debounce value: {debouncedText}</p> </div> ) } 
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)