← All React exercises

React implementation · 08

UseDebounce()

StatusNot taken

Problem

For a frequently changing value like text input you might want to debounce the changes. Implement useDebounce() to achieve this. function App() { const [value, setValue] = useState(...) // this value changes frequently, const debouncedValue = useDebounce(value, 1000) // now it is debounced } The logic should be similar to 6. implement basic debounce()

Solution

Review after your attempt
solution.tsx
1For more about debounce, check out 6. implement basic debounce() and 7. implement debounce() with leading & trailing option
2
3By "debounce the changes", it means that debouncedValue should not change that frequently as value. So we can just store the debouncedValue in a state and update it in a debounced function.
4
5Following is a pretty straightforward solution.
6
7import { useState, useEffect } from "react";
8export function useDebounce<T>(value: T, delay: number): T {
9  const [state, setState] = useState(value);
10  useEffect(() => {
11    const timer = setTimeout(() => {
12      setState(value);
13    }, delay);
14    return () => clearTimeout(timer);
15  }, [value, delay]);
16  return state;
17}
18
19The problem doesn't specify how we should handle the case where only delay changes. In above code, the timer will be still reset if only delay has changed. It is a good idea to check with your interviewer before rushing to code.