Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
How can I have dynamic function to pass in debounce function

I want implement different api search in one React component and I using custom hook.

 const { request:requestOne, data, loading} = useApi(searchOneApiConfig);
 const { request:requestTwo, data, loading} = useApi(searchTwoApiConfig);
 const { request:requestThree, data, loading} = useApi(searchThreeApiConfig);

now I have to use a useCallback(debounce... for each one like:

const SearchLazyQueryOne = useCallback(debounce(requestOne, DEBOUNCED_TIME, LazyQueryConfig), []);
const SearchLazyQueryTwo = useCallback(debounce(requestTwo, DEBOUNCED_TIME, LazyQueryConfig), []); 
const SearchLazyQueryThree = useCallback(debounce(requestThree DEBOUNCED_TIME, LazyQueryConfig), []);

My question is how can I have single "searchLazyQuery" and pass dynamic request function?

(I'm using Lodash's debounce.)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

So it sounds like you want to use:

searchLazyQuery(requestTwo, /*...args*/)

...while debouncing the calls to requestTwo. That will require keeping track of the debounced functions and using the matching one (or creating one as needed).

You can store the debounced versions of the function in a Map. Here's a sketch of a hook that does that:

const useDynamicDebounce = (debouncedTime, config) => {
    // Using a ref to provide a stability guarantee on the function we return
    const ref = useRef(null);
    if (!ref.current) {
        // A map to keep track of debounced functions
        const debouncedMap = new Map();
        // The function we return
        ref.current = (fn, ...args) => {
            // Get the debounced version of this function
            let debounced = debouncedMap.get(fn);
            if (!debounced) {
                // Don't have one yet, create it
                debounced = debounce(fn, debouncedTime, config);
                debouncedMap.set(fn, debounced);
            }
            // Do the call
            return debounced(...args);
        };
    }
    return ref.current;
};

Using it in your component:

const searchLazyQuery = useDynamicDebounce(DEBOUNCED_TIME, LazyQueryConfig);

Then use searchLazyQuery(requestTwo, "args", "for", "requestTwo") (for example).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!