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

160
Views
Usage of useRef with debounce function

I have the following setup in a react component where I have used the debounce function from throttle-debounce package to log the input value for testing ( actually calling an API to fetch data ).

import React, { useState, useRef } from 'react';
import debounce from 'throttle-debounce/debounce';

const MyComponent = () => {
  const [localSearchQuery, setLocalSearchQuery] = useState('');
  
  const setSearchQueryInParams = debounce(2000, value => console.log(value))

  const setSearchQuery = value => {
    setLocalSearchQuery(value);
    setSearchQueryInParams(value);
  };

  return (
    <>
      <Input
        value={localSearchQuery}
        onChange={setSearchQuery}
      />;
    </>
  );
};

But, it's not working as expected. If I type hello in the input box, I get the following output in console:

h
he
hel
hell
hello

However, if I wrap the debounce function with useRef, it works as expected

const setSearchQueryInParams = useRef(debounce(2000, value => console.log(value))).current
Input: hello
Output in console: hello

My question is, why the debounce function is not working without useRef and how useRef is functioning here to get the desired output?

Thank you for the help.

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

0

You'll want to use useCallback, with an empty dependency array, nstead of useRef:

import React, { useState, useCallback } from 'react';
import debounce from 'throttle-debounce/debounce';

const MyComponent = () => {
  const [localSearchQuery, setLocalSearchQuery] = useState('');
  
  const setSearchQueryInParams = useCallback(debounce(2000, value => console.log(value)), []);

  const setSearchQuery = value => {
    setLocalSearchQuery(value);
    setSearchQueryInParams(value);
  };

  return (
    <>
      <Input
        value={localSearchQuery}
        onChange={setSearchQuery}
      />;
    </>
  );
};

The reason is that calling debounce always returns a new function, so you need to store that function across rerenders.

Without that, it has no memory of the setTimeouts it internally calls so it can't use them to debounce properly.

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!