Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Last active January 9, 2020 15:53
Show Gist options
  • Save simbathesailor/aff2228f05e2db0117314cf9329477a9 to your computer and use it in GitHub Desktop.
Save simbathesailor/aff2228f05e2db0117314cf9329477a9 to your computer and use it in GitHub Desktop.
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