cf.completefrontend

Write the codeMedium

Write a useDebouncedValue hook

Write useDebouncedValue(value, delay). It returns a copy of value that waits: it only takes a new value once value has stayed the same for delay milliseconds. A search box can show what you type at once but search for the debounced value, so it doesn't send a request on every key press.

The first render returns value straight away. Each change starts the wait again, and a value that's replaced before its wait ends is never returned. Keep at most one timer waiting at a time, and leave none behind when the component goes away. A change to delay applies to the next wait.

function TeaSearch() {
  const [query, setQuery] = useState("");
  const search = useDebouncedValue(query, 300);
  const results = useSearchResults(search);
  // Show query in the input, and results below it.
}
Write this (useDebouncedValue.js)
import { useEffect, useState } from "react";
 
export function useDebouncedValue(value, delay) {
  // Return value once it has stopped changing for delay milliseconds.
  return value;
}
The checks your code must pass
  • starts with the value it's given
  • a search box shows the query only once typing stops
  • never returns a value that was replaced during its wait
  • keeps one timer while the value keeps changing
  • clears its timer when the component goes away
  • waits for the new delay after it changes

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…