1.0.1 • Published 5 months ago
react-dbounce v1.0.1
react-dbounce
A lightweight and reusable React hook for debouncing values. Perfect for handling user input, search bars, or any scenario where you want to delay updates to improve performance.
Features
- Simple and easy to use.
- Works with any type of value (strings, numbers, objects, etc.).
- Lightweight and dependency-free (except for React).
- Fully customizable debounce delay.
Installation
Install the package via npm or yarn
npm install react-dbounce
Usage Import the useDebounce hook and use it in your React components.
Example: Debouncing a Search Input
import React, { useState, useEffect } from "react";
import { useDebounce } from "react-dbounce";
function SearchBar() {
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearchTerm = useDebounce(searchTerm, 500);
useEffect(() => {
if (debouncedSearchTerm) {
console.log("Send API request with:", debouncedSearchTerm);
// Trigger your API call here
}
}, [debouncedSearchTerm]);
return (
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
export default SearchBar;
Example: Debouncing a Counter
import React, { useState } from "react";
import { useDebounce } from "react-dbounce";
function Counter() {
const [count, setCount] = useState(0);
const debouncedCount = useDebounce(count, 300);
return (
<div>
<p>Count {count}</p>
<p>Debounced {debouncedCount}</p>
<buttonClick={() => setCount(count + 1)}>Increment</button </div>
);
}
export default Counter;
API
useDebounce(value, delay)
Parameters:
value (any): The value to debounce.
delay (number): The debounce delay in milliseconds.
Returns:
debouncedValue (any):
The debounced value.
Why Use This Package? Debouncing is a common requirement in React applications, especially when dealing with user input or expensive operations like API calls. This package provides a simple, reusable solution that saves you time and effort.