Created
July 3, 2020 11:49
-
-
Save goodlifeinc/a65c747789a14fcf230d45174c713863 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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