loading...
Cover image for Use lodash.debounce inside a function component in React

Use lodash.debounce inside a function component in React

reflexgravity profile image Joel D Souza Updated on ・1 min read

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>
    )

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]);

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]);

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} />
}

Posted on Jun 16 by:

reflexgravity profile

Joel D Souza

@reflexgravity

Building reactjs apps at Kapture CRM. he/him. Writing bugs and then fixing them.

Discussion

markdown guide