DEV Community

Cover image for Use lodash.debounce inside a function component in React
Joel D Souza
Joel D Souza

Posted on • Edited on

18 5

Use lodash.debounce inside a function component in React

This is my second post.

In this post I'll explain how to debounce a function inside a function react component using lodash.debounce. We'll create a search app that'll search only when there's a gap of 500ms.

Let's first create a basic search component.

    const [userQuery, setUserQuery] = useState("")

    const onChange = e => {
          setUserQuery(e.target.value);
    };

    return (
      <div>
         <input
             type="text"
             value={userQuery}
             onChange={onChange}
         />
      </div>
    )
Enter fullscreen mode Exit fullscreen mode

We'll create a function delayedQuery that'll call the api after a gap of 500ms.

Make sure you wrap it around useCallback to update the function only when userQuery updates.

const updateQuery = () => {
    // A search query api call.
    sendQuery(userQuery)
};

const delayedQuery = useCallback(debounce(updateQuery, 500), [userQuery]);
Enter fullscreen mode Exit fullscreen mode

We'll call delayedQuery inside useEffect only when the value of userQuery changes. We should also return delayedQuery.cancel to cancel previous calls during useEffect cleanup.

useEffect(() => {
   delayedQuery();

   // Cancel previous debounce calls during useEffect cleanup.
   return delayedQuery.cancel;
}, [userQuery, delayedQuery]);
Enter fullscreen mode Exit fullscreen mode

So, our debounced search is now implemented. Below is the complete code. There is also a codesandbox link for you to play around.

import debounce from 'lodash.debounce'
...

function searchApp() {
const [userQuery, setUserQuery] = useState("")

const updateQuery = () => {
    // A search query api call.
    sendQuery(userQuery)
};

const delayedQuery = useCallback(debounce(updateQuery, 500), [userQuery]);

const onChange = e => {
   setUserQuery(e.target.value);
};

useEffect(() => {
   delayedQuery();

   // Cancel the debounce on useEffect cleanup.
   return delayedQuery.cancel;
}, [userQuery, delayedQuery]);

return <input onChange={onChange} value={userQuery} />
}
Enter fullscreen mode Exit fullscreen mode

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (4)

Collapse
 
kfunk profile image
Kevin Funk

This seems like an anti-pattern for how lodash.debounce is meant to be used. Sure it 'works', but new debounce functions are constantly being run. As a side effect, the additional options don't work. Try out using {maxWait: 500} (should wait at most, 500ms before firing the callback), it doesn't work.

Collapse
 
ace3 profile image
Ignasius Wahyudi

thanks, this is what i need exactly.

cheers.

Collapse
 
huydzzz profile image
Pơ Híp

thank u

Collapse
 
cameronapak profile image
cameronapak

This was very helpful. Thank you!

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay