Skip to content

Commit

Permalink
Merge pull request #88 from JohnsonMao/feature/use-auto-reset-hook
Browse files Browse the repository at this point in the history
✨ use auto reset hook
  • Loading branch information
JohnsonMao authored Sep 22, 2023
2 parents 0826cec + da5c390 commit 116b183
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/hooks/__tests__/useAutoReset.test.ts
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 }
);
});
});
29 changes: 29 additions & 0 deletions src/hooks/useAutoReset.ts
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;

0 comments on commit 116b183

Please sign in to comment.