Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useDebouncedEffect.jsx
function useDebouncedEffect(
callback,
dependency,
timeout = 2000,
options = { trailing: true, leading: false }
) {
const { leading, trailing } = options;
// the source of truth will be _dependencyRef.current always
const [_dependency, _setdependency] = React.useState(dependency);
// making use of second approach here we discussed above
const makeChangeTodependency = React.useCallback(
_.debounce(
dependency => {
console.log("runnign makeChangeTodependency", dependency);
_setdependency(dependency);
},
timeout,
{ trailing, leading }
),
[trailing, leading, timeout]
);
React.useEffect(() => {
if (dependency) {
makeChangeTodependency(dependency);
}
}, dependency);
React.useEffect(callback, _dependency);
}
function ChildComponent({ value, onChange }) {
function makeApiCallRaw(value) {
console.log("make api call with value", value);
}
useDebouncedEffect(
() => {
makeApiCallRaw(value);
},
[value],
2000
);
useDebouncedEffect(
() => {
console.log("Hola !!");
},
[value],
3000
);
useDebouncedEffect(
() => {
console.log("cool !!");
},
[value],
5000
);
return (
<input
defaultValue={value}
value={value}
onChange={e => {
onChange(e.target.value); // non debounced
// makeApiCall(e.target.value) // debounced
}}
/>
);
}
function App() {
const [value, setValue] = React.useState("");
return (
<div>
Hello World
<ChildComponent value={value} onChange={setValue} />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment