-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #88 from JohnsonMao/feature/use-auto-reset-hook
✨ use auto reset hook
- Loading branch information
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { act, renderHook, waitFor } from '@testing-library/react'; | ||
import useAutoReset from '../useAutoReset'; | ||
|
||
describe('useAutoReset hook', () => { | ||
it('should reset state to initial value after a specified delay', async () => { | ||
const initialValue = false; | ||
const newValue = true; | ||
const { result } = renderHook(() => useAutoReset(initialValue)); | ||
|
||
expect(result.current[0]).toBe(initialValue); | ||
|
||
act(() => result.current[1](newValue)); | ||
|
||
expect(result.current[0]).toBe(newValue); | ||
|
||
await waitFor( | ||
() => expect(result.current[0]).toBe(initialValue), | ||
{ timeout: 2000 } | ||
); | ||
}); | ||
}); |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { useEffect, useRef, useState } from 'react'; | ||
|
||
/** | ||
* Custom hook that resets a value to its initial state after a specified delay. | ||
* | ||
* @param initialValue - The initial value. | ||
* @param resetDelayMs - The reset delay in milliseconds. Default is 1000. | ||
* @returns A tuple containing the current value, and a function to set a new value. | ||
*/ | ||
function useAutoReset<T>(initialValue: T, resetDelayMs = 1000) { | ||
const [internalValue, setInternalValue] = useState(initialValue); | ||
const timerRef = useRef<NodeJS.Timeout | null>(null); | ||
|
||
const clearTimer = () => { | ||
if (timerRef.current) clearTimeout(timerRef.current); | ||
}; | ||
|
||
const setValue = (newValue: T) => { | ||
setInternalValue(newValue); | ||
clearTimer(); | ||
timerRef.current = setTimeout(() => setInternalValue(initialValue), resetDelayMs); | ||
}; | ||
|
||
useEffect(() => clearTimer, []); | ||
|
||
return [internalValue, setValue] as const; | ||
} | ||
|
||
export default useAutoReset; |