Skip to content
This repository was archived by the owner on Sep 1, 2024. It is now read-only.

Created useTimeout solution #52

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions useTimeout solution
Original file line number Diff line number Diff line change
@@ -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 (
<>
<p>Count : {count}</p>
<button onClick={handleCount}>Increment</button>
</>
)
}