https://github.com/nas5w/use-effect-debounced
A custom React hook that provides a debounced version of useEffect.
https://github.com/nas5w/use-effect-debounced
javascript react react-hooks reactjs useeffect
Last synced: 4 months ago
JSON representation
A custom React hook that provides a debounced version of useEffect.
- Host: GitHub
- URL: https://github.com/nas5w/use-effect-debounced
- Owner: nas5w
- Created: 2019-04-06T22:08:32.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-04-06T22:18:39.000Z (over 6 years ago)
- Last Synced: 2025-04-19T20:44:58.007Z (6 months ago)
- Topics: javascript, react, react-hooks, reactjs, useeffect
- Language: HTML
- Size: 153 KB
- Stars: 5
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# useEffectDebounced
This repository demonstrates creating a custom hook called `useEffectDebounced`. It works just like `useEffect` except the function you pass to `useEffectDebounced` only be executed after a user-specified amount of time (and only if the the parameters on which the effect depends do not change).
## Implementation
the `useEffectDebounced` hook is implemented as follows:
```javascript
import { useEffect } from "react";const useEffectDebounced = (func, values, time) => {
useEffect(() => {
let db = setTimeout(() => {
func();
}, time);return () => clearTimeout(db);
}, values);
};export default useEffectDebounced;
```The passed function `func` is executed in a `setTimeout` after the user specified `time`. However, if one of the `values` the hook depends on is changed, the clean-up function `() => clearTimeout(db)` is executed, meaning `func` will not execute.
## Example Usage
This application includes an example usage in which a textbox is used to filter through a list of countries. The filtering is done in the `useEffectDebounced` hook, meaning the filtering will not occur until the specified period of time has passed without additional changes to the textbox.
```javascript
import React, { useState } from "react";
import useEffectDebounced from "./useEffectDebounced";
import countries from "./countries";const App = () => {
const [filteredCountries, setFilteredCountries] = useState(countries);
const [search, setSearch] = useState("");useEffectDebounced(
() => {
const filtered = countries.filter(country =>
country.name.toLowerCase().includes(search.toLowerCase())
);
setFilteredCountries(filtered);
},
[search],
1000
);return (
setSearch(e.target.value)} />
{filteredCountries &&
filteredCountries.map((country, index) => {
return- {country.name}
;
})}
);
};export default App;
```
## Feedback
I would appreciate any feedback you have on this custom hook!