From 841d60c558ac75547b4fa9392a1f314f1d67f519 Mon Sep 17 00:00:00 2001 From: Rish-it <201b214@juetguna.in> Date: Wed, 27 Nov 2024 14:08:16 +0530 Subject: [PATCH] debouncing added --- Documentations/debouncing_in_react.md | 142 ++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 Documentations/debouncing_in_react.md diff --git a/Documentations/debouncing_in_react.md b/Documentations/debouncing_in_react.md new file mode 100644 index 0000000..3cb10e9 --- /dev/null +++ b/Documentations/debouncing_in_react.md @@ -0,0 +1,142 @@ + +--- +title: "Debouncing in React: Optimizing Performance and User Experience" +description: "Learn how to use debouncing in React to enhance performance and improve user interactions." +author: "Rishit Sharma" +date: "2024-11-27" +--- + +## Introduction + +Debouncing is like a performance booster for your React apps. It helps slow down the rate at which a function runs, making sure things don’t get too hectic. Imagine you have a search input field or a resizing event that triggers a bunch of actions. Debouncing can help you handle those things smoothly. In this guide, we’ll dive into debouncing, explore its uses, and show you how to use it in your React projects. + + +## Main Content + +### What is Debouncing? + +Debouncing is like a bouncer at a club. It makes sure that a function only gets called once after a certain amount of time, even if you keep hitting the button. This way, you don’t have to worry about doing the same thing over and over again, and it saves you from having to make too many requests to the server. + + + +### Use Cases + +1. **Search Boxes:** Delay API calls as users type, reducing unnecessary network requests. +2. **Window Resize Events:** Avoid repeated computations during rapid resizing. +3. **Button Clicks:** Prevent multiple submissions caused by rapid user clicks. + +### Implementing Debounce in React + +#### Using `lodash` for Debouncing + +The `lodash` library provides a `debounce` function that is simple to integrate. + +```bash +npm install lodash +``` + +```javascript +import { debounce } from 'lodash'; +import { useState, useCallback } from 'react'; + +function SearchComponent() { + const [query, setQuery] = useState(''); + + const fetchResults = (searchTerm) => { + console.log('Fetching results for:', searchTerm); + // all API logic goes here + }; + + const debouncedFetch = useCallback(debounce(fetchResults, 500), []); + + const handleChange = (event) => { + setQuery(event.target.value); + debouncedFetch(event.target.value); + }; + + return ( +