2022年7月16日星期六

useDebounce for input and update search (real time search)

import { useEffect, useState } from "react";

const useDebounce = (initialValue = "", delay) => {

  const [actualValue, setActualValue] = useState(initialValue);

  const [debounceValue, setDebounceValue] = useState(initialValue);

  useEffect(() => {

    const debounceId = setTimeout(() => setDebounceValue(actualValue), delay);

    return () => clearTimeout(debounceId);

  }, [actualValue, delay]);

  return [debounceValue, setActualValue];

};


----------------------------

Defined return () => { /*code/* }  runs on component unmount 

React does so by "mounting" (adding nodes to the DOM), "unmounting" (removing them from the DOM)


Usage:

const [debouncedSearchStr, setDebouncedSearchStr] = useDebounce('', 500);

沒有留言:

發佈留言

[Fixed] some windows chrome, scrolling has glitch position not accurate

   [Fixed] some windows chrome, scrolling has glitch position not accurate Smooth Scrolling Flag 📜 Chrome has an experimental "smooth ...