
Avoid multiple clicks using debounce with react hooks
Why debounce with react hooks? We all come across that one button users keep on pressing until the data is loaded. Without guarding your code with every sort of if conditions, you can guard this by debouncing. For multiple tap scenarios, you can either propagate the event at the first tap/click or the last one.
Debouncing with hooks can be a bit tricky to sort out. The problem is the functional components in react will initialize the function when rendering. To avoid that and register a debouncing function you can use the following method.
How to use debounce with react hooks
We will be using the lodash debounce function https://lodash.com/docs/4.17.4 to debounce and avoid multiple tap action. In this simple example, a tap on the button will be used to explain how to use the debounce function.
Here we use useCallback
hook to avoid updating the debounce function when re-rendering the component on state change. This is very important in these kind of implementations to avoid initializing functions every time when renders or state changes.
Note that we have passed clicks
as a parameter to avoid the debounce function using the initial values in the function callback. For these kinds of state updates, you may need to use a closure that can be updated from parameters provided to the debounce function.
const {useState, useCallback } = React;
const INTERVAL = 1000;
const Button = ({label, onClick}) => {
return (
<div className="button" onClick={onClick}>{label}</div>
);
}
const App = () => {
const [clicks, setClicks] = useState(0);
// Add once click to the existing state value
const clickOnce = (click) => {
setClicks(click + 1);
}
// debounce the click function
// note that the clicks are passed as a parameter to avoid repeating the initial value
const debouncedClick = useCallback(_.debounce((clicks) => {
clickOnce(clicks);
}, INTERVAL, {leading: true, trailing: false, maxWait: INTERVAL}), []);
return (
<div>
<Button label="Click Button" clicks={clicks} onClick={() => debouncedClick(clicks)}/>
<div className="click-count">Click Count: {clicks}</div>
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById('app')
);
Above is the codepen example. Here we have used an extra button component to increase the count. When you tapping the button, you will notice that the count is increased every second which is the INTERVAL const declared at the beginning of the js script. Also, you can use different kinds of options to suit your needs. The maxWait
and interval
are two important parameters you would need to understand better as well.
See the Pen Debounce using React hooks by Sandaruwan Nanayakkara (@sandaruny) on CodePen.
Also if you need to use debounce on react component class checkout following link:
114 COMMENTS
I’d like to thank you for the efforts you’ve put in penning this website. I am hoping to check out the same high-grade blog posts from you later on as well. In fact, your creative writing abilities has motivated me to get my own site now.
You are taking tadalafil medicines for treating chest pain or blood pressure for any nitrate-based medicine, avoid this drug cialis for sale
Thanks for the ideas you write about through your blog. In addition, many young women who become pregnant will not even attempt to get medical health insurance because they dread they won’t qualify. Although many states now require that insurers present coverage in spite of the pre-existing conditions. Costs on these types of guaranteed programs are usually bigger, but when with the high cost of medical care it may be the safer way to go to protect the financial future.
cialis and viagra sales RNA, DNA, and proteins will likely garner increased attention from the scientists in the coming years, to innovate mitophagy targeted interferences and or development of novel therapies for improving aging associated lifespan and other diseases including cancer
selective serotonin reuptake inhibitor SSRI stromectol info
tamoxifen uterine cancer Hi Imm, I understand your concern for Girlie and these worrisome symptoms
[url=http://trazodone.gives/]trazodone prescription medicine[/url]
Having read this I believed it was very informative. I appreciate you spending some time and energy to put this content together. I once again find myself personally spending way too much time both reading and commenting. But so what, it was still worth it!
[url=http://dexamethasone.charity/]dexamethasone tablets canada[/url]
[url=https://cymbalta.digital/]cymbalta 180mg[/url]
[url=https://piroxicam.best/]buy piroxicam gel[/url]
benicar 20 mg price [url=https://benicar.ink/]benicar cost[/url] how much does benicar cost
Your writing style is engaging and your ideas are well-articulated. I appreciate the fresh perspective you bring to the topic.
[url=https://levothyroxine.foundation/]synthroid 75 mcg tablet[/url]
سعر آلة لحام البولي إيثيلين
أكبر شركة لانتاج أنابيب البولي ايثيلين و يو بي سي ومستلزماتها للمنتجات الصناعية في عيراق
المديرية العامة لاعداد المعلمين والتدريب والتطوير التربوي. شكرًا لك..
دولار مقابل الدينار العراقي في بورصة الكفاح اليوم شكرًا لك..
Thank you for sharing your insights and expertise on this topic. Your article is well-researched and provides valuable information for readers.
This article is highly informative and has helped me to gain a better understanding of the topic.
[url=https://levaquina.online/]levaquin price[/url]
I enjoyed reading this article from start to finish. Your writing style is clear and easy to follow, and your ideas are presented in a logical and compelling manner.
Your article is a great resource for anyone looking to learn more about this topic. Thank you for compiling this information.
Your passion for this subject shines through in your writing. It’s clear you care deeply about this issue and want to make a difference.
I appreciate the depth and breadth of research you put into this article. It’s evident that you are passionate about the subject.
The factory’s adherence to environmental sustainability is demonstrated through their use of eco-friendly materials and energy-efficient manufacturing practices. Elitepipe Plastic Factory
The Elitepipe Plastic Factory in Iraq is an industry leader known for its commitment to delivering high-quality plastic pipes and fittings. Elitepipe Plastic Factory
يعتبر مصنع إيليت بايب Elite Pipe في العراق رائدًا صناعيًا معروفًا بالتزامه بتقديم الأنابيب والتجهيزات البلاستيكية عالية الجودة.
Thank you for sharing your expertise and knowledge on this topic. Your insights are invaluable.
Elitepipe Plastic Factory’s fittings undergo rigorous quality control processes to ensure that they meet the most stringent performance and durability requirements. Elitepipe Plastic Factory
Your article is a great starting point for anyone looking to get involved in this issue. The information is presented in a way that is both accessible and informative.
تخضع تجهيزات مصنع إيليت بايب Elite Pipeلعمليات مراقبة جودة صارمة للتأكد من أنها تلبي متطلبات الأداء والمتانة الأكثر صرامة.
Your article is a great example of how to present a topic in a clear and concise way. Thank you for sharing.
مرافق تصنيع إيليت بايب Elite Pipe مجهزة بأحدث الآلات ، مما يتيح عمليات الإنتاج الفعالة وجودة المنتج المتسقة.
مع مجموعة واسعة من التركيبات ، بما في ذلك الأكواع ، المحملات ، الوصلات ، وأكثر من ذلك ، يقدم مصنع إيليت بايب Elite Pipe حلولًا شاملة لأنظمة وتركيبات الأنابيب المختلفة.
[url=http://cafergot.charity/]cafergot pills[/url]
The structure of this article is well-organized and easy to follow.
The Elitepipe Plastic Factory in Iraq is an industry leader known for its commitment to delivering high-quality plastic pipes and fittings. Elitepipe Plastic Factory
The factory’s dedication to quality is evident in the superior performance of their HDPE pipes, which are known for their exceptional strength and durability. Elitepipe Plastic Factory
The factory’s commitment to innovation is reflected in their continuous research and development efforts to enhance the design and functionality of their HDPE and uPVC fittings. Elitepipe Plastic Factory
[url=http://vermox.trade/]vermox 500mg tablet price[/url]
[url=https://escitalopram.party/]buy lexapro online india[/url]
[url=http://effexor.party/]225 effexor[/url]
[url=https://citalopram.trade/]price of celexa[/url]
[url=https://amoxicillinbact.online/]augmentin xr[/url]
[url=http://lyricanx.online/]lyrica 75 mg[/url]
[url=https://atarax.cyou/]atarax medicine in india[/url]
[url=http://synthroid.boutique/]synthroid 50mg[/url]
[url=http://trazodone.best/]trazodone 300 mg tablet[/url]
[url=https://amoxicillin.cyou/]amoxicillin 250 mg tablet[/url]
[url=http://zoloft.cfd/]buy zoloft india[/url]
[url=http://accutane.guru/]generic accutane cost[/url]
[url=https://effexor.cyou/]effexor price australia[/url]
[url=https://tadalafil.cfd/]where to buy tadalafil cheap[/url]
[url=https://semaglutidetabs.online/]buy rybelsus from canada[/url]
[url=https://rybelsus.download/]buy rybelsus online no script needed[/url]
This is my first time pay a quick visit at here and i am really happy to read everthing at one place
[url=https://semaglutide.company/]rybelsus 14mg[/url]
[url=https://semaglutide.cyou/]wegovy price[/url]
[url=https://semaglutidewegovy.com/]buy semaglutide from canada online[/url]
[url=https://semaglutide.company/]buy semaglutide[/url]
[url=https://semaglutidetabs.online/]wegovy semaglutide tablets[/url]
Your posts always provide me with a new perspective and encourage me to look at things differently Thank you for broadening my horizons
Your posts always provide me with a new perspective and encourage me to look at things differently Thank you for broadening my horizons
[url=https://isynthroid.online/]hair loss synthroid[/url]
I appreciate the thought-provoking questions you raised in your article. It’s important to consider all angles of an issue.
[url=https://prednisoneo.com/]prednisone 50 mg tablet canada[/url]
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
[url=http://azithromycinmds.com/]buy zithromax online australia[/url]
[url=https://olisinopril.online/]prinivil 5mg tablet[/url]
[url=https://bestmedsx.online/]express scripts com pharmacies[/url]
[url=http://lisinoprildrl.online/]medication lisinopril 5 mg[/url]
[url=https://ibaclofen.com/]baclofen 30 mg cream[/url]
[url=https://albuterolo.com/]combivent inhaler price[/url]
[url=https://tretinoineff.online/]buy retin a cream uk[/url]
[url=http://ciproo.online/]ciprofloxacin 500mg online[/url]
[url=https://diflucand.com/]diflucan 150 mg tablets[/url]
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Tus comentarios siempre son bienvenidos, aportan claridad y enfoque.
I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.com/ru/register?ref=V3MG69RO
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.com/register?ref=P9L9FQKY
Enhance your industrial operations with BWER weighbridges, designed for exceptional accuracy and durability to support Iraq’s growing infrastructure and logistics sectors.
Your article helped me a lot, is there any more related content? Thanks! https://accounts.binance.com/uk-UA/register?ref=W0BCQMF1
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
The Best Premium IPTV Service WorldWide!
I have not checked in here for a while as I thought it was getting boring, but the last several posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂
UID_59407105###
berita dana x twitter viral berita dana desa ada disini !
UID_72942561###
Berita Hot! 🔥🔥 Isa Rachmatarwata Tersangka Kasus Jiwasraya Buntut kerugian negara hingga 16,8 Triliun! 😲😲
UID_53550706###
Berita terbaru! 🔥 Isa Rachmatarwata Ditahan Kejagung dalam kasus Jiwasraya. 🚔👮♂️
UID_57092237###
Berita gembira! 🎉 Pasokan Gas 3 Kg di Kramat Jati Kembali Normal 🎊 Siap-siap belanja gas, ya! 💪🔥
UID_72339950###
Heboh! 📣🔥 Unjuk Rasa di Polda Jatim 📢 Menuduh Jokowi Terlibat Korupsi! 😱🔍
UID_27764099###
Ini yang di ganti >>> “Bingung Kenapa 😕❓” Federasi Sepak Bola Pakistan Disanksi FIFA “Baca Penyebabnya Disini! 🧐🔍”
UID_74743238###
Ini dia! 🎉🎉 ASN BKN Ubah Pola Kerja yang baru dan efisien! 🎉🎉.
UID_83344528###
Inilah 🎉🎉 Pupuk Inovatif Kebun Riset Kujang yang bikin Wamen BUMN bangga! 💪🏻🇮🇩
You are my intake, I have few web logs and sometimes run out from brand :). “‘Tis the most tender part of love, each other to forgive.” by John Sheffield.
UID_21891068###
Takjub 😮 dengan fenomena serbu gas? Yuk, baca Warung Tatang Diserbu Warga dan temukan faktanya! 🕵️♀️👀
I do consider all of the concepts you have offered in your post. They’re very convincing and will definitely work. Nonetheless, the posts are too brief for newbies. May you please lengthen them a bit from subsequent time? Thanks for the post.
UID_25978847###
situs terbaik hanya di slot gacor agentotoplay
UID_95859078###
Baru-baru ini, para pemain Mahjong Wins 3 dikejutkan dengan bocoran RTP yang diklaim bisa meningkatkan peluang kemenangan secara signifikan. Banyak yang percaya bahwa informasi ini membantu mereka mendapatkan hasil yang lebih konsisten dalam permainan. Jika Anda ingin tahu lebih lanjut, cek bocoran RTP Mahjong Wins 3 hari ini dan lihat apakah strategi ini benar-benar efektif.
UID_57331425###
Skandal terbaru mengguncang komunitas pecinta game slot setelah seorang admin terkenal, Rachel, dikabarkan tertangkap membocorkan pola kemenangan Gate of Olympus. Banyak yang bertanya-tanya apakah informasi ini benar-benar akurat atau hanya sekadar rumor yang beredar di kalangan pemain. Simak lebih lanjut detailnya dalam artikel admin Rachel tertangkap bocorkan pola Gate of Olympus.
UID_17136916###
Kisah inspiratif datang dari seorang tukang ojek online asal Tangerang yang berhasil membawa pulang hadiah fantastis setelah bermain Mahjong Ways 2. Dengan modal kecil, ia sukses mengubah nasibnya dan meraih kemenangan besar senilai 200 juta rupiah. Penasaran bagaimana caranya? Simak kisah lengkapnya di artikel tukang ojek online menang 200 juta dari Mahjong Ways 2.
UID_87427935###
Cek yuk! 🚍👮♂️Operasi Keselamatan 2025 Polres Ciamis Siapa tahu bus favoritmu jadi sasaran! 😱👍
UID_18563832###
Ini yang di ganti >>> Yuk, ketahui lebih lanjut tentang Syarat Gabung OECD dan Pentingnya Ratifikasi Konvensi Antisuap di sini! 🕵️♀️🔎📚.
UID_83003169###
Kenalan yuk! 🤝 Dengan guru inspiratif ini, Guru Dede Sulaeman yang mengajarkan cara merapikan pakaian di kelasnya. 👕👚🎓
UID_97211224###
Yuk, sehat bersama! 👨⚕️👩⚕️ Cek kondisi tubuh kamu di Program Cek Kesehatan Gratis sekarang juga! 💉🌡️ Selalu jaga kesehatan, ya! 🏥💖
Generally I do not learn article on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing taste has been amazed me. Thank you, quite great article.
You actually make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!
Your article helped me a lot, is there any more related content? Thanks!
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?