Created
May 10, 2019 16:59
-
-
Save terrysahaidak/bfb68ad1f4c7a653272529f29c1ebd46 to your computer and use it in GitHub Desktop.
Useful hook to suspend your prop change
This file contains 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
export default function useSuspendedProp(prop, timeout = 500) { | |
const initialValue = useRef(prop); | |
const [copy, setCopy] = useState(prop); | |
const timeoutRef = useRef(null); | |
useEffect(() => { | |
clearTimeout(timeoutRef.current); | |
if ( | |
initialValue.current === prop && | |
initialValue.current !== copy | |
) { | |
setCopy(prop); | |
} else { | |
timeoutRef.current = setTimeout(() => { | |
setCopy(prop); | |
}, timeout); | |
} | |
return () => clearTimeout(timeoutRef.current); | |
}, [prop]); | |
return copy; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment