This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for React Coding Question on BFE.dev
2. useTimeout()
Here's an example implementation of the useTimeout()
hook that meets the requirements specified in the question:
import { useState, useEffect } from 'react';function useTimeout(callback, delay) { const [timerId, setTimerId] = useState(null); useEffect(() => { if (timerId) { clearTimeout(timerId); } if (callback && delay !== null) { setTimerId(setTimeout(callback, delay)); } return () => { if (timerId) { clearTimeout(timerId); } }; }, [callback, delay]); return timerId;}
The hook returns a timerId
value that can be used to cancel the timer before it fires. Here's an example usage of the hook in a component:
import { useState } from 'react';import useTimeout from './useTimeout';function Example() { const [count, setCount] = useState(0); const handleTimer = () => { setCount(count + 1); }; useTimeout(handleTimer, 1000); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(0)}>Reset Count</button> </div> );}
In this example, a timer is started with a 1 second delay. When the timer fires, the handleTimer()
function is called, which increments the count
state value. Note that the timer is automatically reset if the delay value changes, but not if the handleTimer
function reference changes. This ensures that the timer is only restarted when necessary, and prevents unnecessary re-renders of the component.