惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Debounce and Throttle Callbacks in React
Dmitri Pavlutin · 2021-05-11 · via Dmitri Pavlutin Blog

When a React component handles bursting events like window resize, scrolling, user typing into an input, etc. — it's wise to soften the handlers of these events.

Otherwise, if the handlers are invoked too often you risk making the application lagging or even unresponsive for a few seconds. In this regards, debouncing and throttling techniques can help you control the invocation of the event handlers.

In this post, you'll learn how to correctly use React hooks to apply debouncing and throttling techniques to callbacks in React.

1. The callback without debouncing

The component <FilterList> accepts a big list of names (at least 200 records). The component has an input field where the user types a query — as result the names are filtered by the query.

Here's the first version of <FilterList> component:


import { useState } from 'react';

export function FilterList({ names }) {

const [query, setQuery] = useState('');

let filteredNames = names;

if (query !== "") {

filteredNames = names.filter((name) => {

return name.toLowerCase().includes(query.toLowerCase());

});

}

const changeHandler = event => {

setQuery(event.target.value);

};

return (

<div>

<input

onChange={changeHandler}

type="text"

placeholder="Type a query..."

/>

{filteredNames.map(name => <div key={name}>{name}</div>)}

</div>

);

}


Open the demo.

Type the query into the input field, and you'll see the list filtered for every introduced character.

For example, if you type char by char the word "Michael", then the component will display flashes of filtered lists for the queries M, Mi, Mic, Mich, Micha, Michae, Michael. However, the user usually wants to see just one filter result: for the word Michael.

Let's soften the filtering by applying 300ms time debouncing on the changeHandler callback function.

2. Debouncing a callback, the first attempt

To debounce the changeHandler function I'm going to use the lodash.debounce package (but you can use any other library you like).

First, let's look at how to use the debounce() function:


import debounce from 'lodash.debounce';

const debouncedCallback = debounce(callback, waitTime);


debounce() function accepts a callback function as argument, and returns a debounced version of that function.

When the debounced function debouncedCallback gets invoked multiple times, in bursts, it will invoke the callback only after waitTime has passed after the last invocation.

The debouncing fits nicely to soften the filtering inside the <FilterList>: you can apply a debounce of 300ms to changeHandler.

A nuance with debouncing of changeHandler inside a React component is that the debounced version of the function should remain the same between component re-renderings.

The first approach is to use useCallback(callback, dependencies) to keep one instance of the debounced function between component re-renderings.


import { useState, useCallback } from 'react';

import debounce from 'lodash.debounce';

export function FilterList({ names }) {

const [query, setQuery] = useState("");

let filteredNames = names;

if (query !== "") {

filteredNames = names.filter((name) => {

return name.toLowerCase().includes(query.toLowerCase());

});

}

const changeHandler = event => {

setQuery(event.target.value);

};

const debouncedChangeHandler = useCallback(

debounce(changeHandler, 300)

, []);

return (

<div>

<input

onChange={debouncedChangeHandler}

type="text"

placeholder="Type a query..."

/>

{filteredNames.map(name => <div key={name}>{name}</div>)}

</div>

);

}


Open the demo.

debounce(changeHandler, 300) creates a debounced version of the event handler, and useCallback(debounce(changeHandler, 300), []) makes sure to return the same instance of the debounced callback between re-renderings.

Note: the approach also works with creating throttled functions, e.g. useCallback(throttle(callback, time), []).

Open the demo and type a query: you'll see that the list is filtered with a delay of 300ms after the last typing: which brings a softer and better user experience.

However... this implementation has a small performance issue: each time the component re-renders, a new instance of the debounced function is created by the debounce(changeHandler, 300).

That's not a problem regarding the correctness: useCallback() makes sure to return the same debounced function instance. But it would be wise to avoid calling debounce(...) on each rendering.

Let's see how to avoid creating debounced functions on each render in the next section.

3. Debouncing a callback, second attempt

Fortunately, using useMemo() hook as an alternative to useCallback() is a more performant choice:


import { useState, useMemo } from 'react';

import debounce from 'lodash.debounce';

export function FilterList({ names }) {

const [query, setQuery] = useState("");

let filteredNames = names;

if (query !== "") {

filteredNames = names.filter((name) => {

return name.toLowerCase().includes(query.toLowerCase());

});

}

const changeHandler = (event) => {

setQuery(event.target.value);

};

const debouncedChangeHandler = useMemo(

() => debounce(changeHandler, 300)

, []);

return (

<div>

<input

onChange={debouncedChangeHandler}

type="text"

placeholder="Type a query..."

/>

{filteredNames.map(name => <div key={name}>{name}</div>)}

</div>

);

}


Open the demo.

useMemo(() => debounce(changeHandler, 300), []) memoizes the debounced handler, but also calls debounce() only during initial rendering of the component.

This approach also works with creating throttled functions: useMemo(() => throttle(callback, time), []).

Open the demo and check if typing into the input field is still debounced.

Note: Currently useMemo() re-calculates the memoized value only when the deps change. But possibly in the future React could "forget" time to time the memoized value, which could lead to re-recreation of debounced callbacks even if the deps haven't changed. The useCallback solution presented above doesn't have this nuance.

4. Be careful with dependencies

If the debounced handler uses props or state, to avoid creating stale closures, I recommend setting up correctly the dependencies of useMemo():


import { useMemo } from 'react';

import debounce from 'lodash.debounce';

function MyComponent({ prop }) {

const [value, setValue] = useState('');

const eventHandler = () => {

// the event uses `prop` and `value`

};

const debouncedEventHandler = useMemo(

() => debounce(eventHandler, 300)

, [prop, stateValue]);

// ...

}


Properly setting the dependencies guarantees refreshing the debounced closure.

5. Cleanup

Because debouncing and throttling execute the function with a delay, you might end up in a situation when the function is executed after the component is unmounted.

When no longer needed, it is recommended to cancel debouncing and throttling.

The debounce and throttle implementations usually provide a special method to cancel the execution. For example lodash's debounce() provides debouncedCallback.cancel() to cancel any scheduled calls.

Here's how you can cancel the debounced function when the component unmounts:


import { useState, useMemo, useEffect } from 'react';

import debounce from 'lodash.debounce';

export function FilterList({ names }) {

// ....

const debouncedChangeHandler = useMemo(

() => debounce(changeHandler, 300)

, []);

// Stop the invocation of the debounced function

// after unmounting

useEffect(() => {

return () => {

debouncedChangeHandler.cancel();

}

}, []);

return (

// ....

);

}


I recommend checking my How to Cleanup Async Effects in React.

6. Conclusion

You have 2 options to create debounced and throttled functions in React: using useCallback() or useMemo() hooks.


import { useMemo } from 'react';

import debounce from 'lodash.debounce';

function MyComponent() {

const eventHandler = () => {

// handle the event...

};

// Option A: useCallback() stores the debounced callback

const debouncedChangeHandler = useCallback(

debounce(changeHandler, 300)

, []);

// Option B: useMemo() stores the debounced callback

const debouncedEventHandler = useMemo(

() => debounce(eventHandler, 300)

, []);

// ...

}


If the debounced or throttled event handler accesses props or state values, do not forget to set the dependencies argument:


// Option A:

useCallback(debouncedCallback, [dep1, dep2, ..., depN])

// Option B:

useMemo(() => debouncedCallback, [dep1, dep2, ..., depN])


What events in your opinion are worth debouncing and throttling?