Skip to content

Instantly share code, notes, and snippets.

@goodlifeinc
Created July 3, 2020 11:49
Show Gist options
  • Save goodlifeinc/a65c747789a14fcf230d45174c713863 to your computer and use it in GitHub Desktop.
Save goodlifeinc/a65c747789a14fcf230d45174c713863 to your computer and use it in GitHub Desktop.
import { useRef, useState, memo, useEffect } from 'react';
import PropTypes from 'prop-types';
const noop = () => {};
const DEFAULT_DEBOUNCE_TIMEOUT = 330; // ms
const Debounced = ({ children, value, onChange, timeout }) => {
const timeoutIdRef = useRef(null);
const [innerValue, setInnerValue] = useState(value);
useEffect(() => {
setInnerValue(value);
}, [value]);
const handleChange = val => {
setInnerValue(val);
clearTimeout(timeoutIdRef.current);
timeoutIdRef.current = setTimeout(() => {
onChange(val);
}, timeout);
};
const debouncedValue = timeoutIdRef.current ? innerValue : value;
return children(debouncedValue, handleChange);
};
Debounced.propTypes = {
children: PropTypes.func.isRequired,
value: PropTypes.any,
onChange: PropTypes.func,
timeout: PropTypes.number
};
Debounced.defaultProps = {
children: noop,
value: null,
onChange: noop,
timeout: DEFAULT_DEBOUNCE_TIMEOUT
};
export default memo(Debounced);
import { useState, useEffect, useRef } from 'react';
function useDebounced({
value = null,
onChange = () => {},
debounceTime = 500
}) {
const timeoutIdRef = useRef(null);
const [innerValue, setInnerValue] = useState(value);
useEffect(() => {
setInnerValue(value);
}, [value]);
const handleChange = e => {
if (value !== null) {
setInnerValue(e.target.value);
}
clearTimeout(timeoutIdRef.current);
timeoutIdRef.current = setTimeout(() => {
onChange(e);
}, debounceTime);
};
const debouncedValue = timeoutIdRef.current ? innerValue : value;
return [debouncedValue, handleChange];
}
export default useDebounced;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment