From aba45ec41037810e850f1ab295042f8392c7aa11 Mon Sep 17 00:00:00 2001 From: Shayak Roychowdhury <69388919+Shayak99@users.noreply.github.com> Date: Sat, 17 Jun 2023 12:03:39 +0530 Subject: [PATCH] Created useTimeout solution --- useTimeout solution | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 useTimeout solution diff --git a/useTimeout solution b/useTimeout solution new file mode 100644 index 00000000..5aeea54a --- /dev/null +++ b/useTimeout solution @@ -0,0 +1,38 @@ +import React , {useEffect, useState, useRef} from 'react'; + +export function useTimeout(callback: () => void, delay: number) { + // your code here + + let timeOut: number|undefined; + const savedCallback = useRef(callback) + savedCallback.current = callback; + + useEffect(() => { + timeOut = setTimeout(() => savedCallback.current(), delay) + + return () => { + clearTimeout(timeOut); + } + }, [delay]); + +} + +// if you want to try your code on the right panel +// remember to export App() component like below + +export function App() { + const [count , setCount] = useState(0); + + const handleCount = () => { + setCount(prev => prev+1); + } + + useTimeout(handleCount, 2000); + + return ( + <> +

Count : {count}

+ + + ) +}