Skip to content

Commit

Permalink
add clear function
Browse files Browse the repository at this point in the history
  • Loading branch information
samanmohamadi committed May 4, 2021
1 parent 96b36cd commit dbb9cd9
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import React, { useEffect, useRef } from 'react';
import { useEffect, useRef } from 'react';

export function useDebouncedEffect(callback, delay, deps = []) {
const firstUpdate = useRef(true);
const data = useRef({ firstTime : true });
useEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
const { firstTime, clearFunc } = data.current;

if (firstTime) {
data.current.firstTime = false;
return;
}

const handler = setTimeout(() => {
if (clearFunc && typeof clearFunc === 'function') {
clearFunc();
}
const handler = setTimeout(() => {
callback();
}, delay);
data.current.clearFunc = callback();
}, delay);

return () => {
clearTimeout(handler);
};
},
return () => {
clearTimeout(handler);
};
},
[delay, ...deps],
);
}
Expand Down

0 comments on commit dbb9cd9

Please sign in to comment.