Skip to content

Commit

Permalink
feat: add useTimeout hook (#65)
Browse files Browse the repository at this point in the history
The useTimeout hook is used to execute a callback after a specified amount of time
  • Loading branch information
immois authored Oct 9, 2023
1 parent cce3f8c commit 743dd1e
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 13 deletions.
5 changes: 5 additions & 0 deletions .changeset/pretty-chicken-agree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@raddix/use-timeout': major
---

Added the useTimeout hook
5 changes: 5 additions & 0 deletions packages/interactions/use-timeout/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# useTimeout

The `useTimeout` hook is used to execute a callback after a specified amount of time. It is similar to the `setTimeout` function, but it is declarative and can be cancelled.

Please refer to the [documentation](https://www.raddix.website/docs/interactions/use-timeout) for more information.
47 changes: 47 additions & 0 deletions packages/interactions/use-timeout/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "@raddix/use-timeout",
"description": "A React hook for handling timeouts",
"version": "0.1.0",
"license": "MIT",
"main": "src/index.ts",
"author": "Moises Machuca Valverde <rolan.machuca@gmail.com> (https://www.moisesmachuca.com)",
"homepage": "https://www.raddix.website",
"repository": {
"type": "git",
"url": "https://github.com/gdvu/raddix.git"
},
"keywords": [
"react-hook",
"react-timeout-hook",
"react-timeout",
"react-use-timeout",
"use-timeout",
"use-timeout-hook",
"hook-timeout"
],
"sideEffects": false,
"scripts": {
"lint": "eslint \"{src,tests}/*.{ts,tsx,css}\"",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"build": "tsup src --dts",
"prepack": "clean-package",
"postpack": "clean-package restore"
},
"files": [
"dist",
"README.md"
],
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"clean-package": "../../../clean-package.config.json",
"tsup": {
"clean": true,
"target": "es2019",
"format": [
"cjs",
"esm"
]
}
}
26 changes: 26 additions & 0 deletions packages/interactions/use-timeout/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useEffect, useRef } from 'react';

type UseTimeout = (cb: () => void, delay: number) => () => void;

export const useTimeout: UseTimeout = (cb, delay) => {
const savedCallback = useRef(cb);
const id = useRef<NodeJS.Timeout | null>(null);

const clearId = () => {
if (!id.current) return;
clearTimeout(id.current);
id.current = null;
};

useEffect(() => {
savedCallback.current = cb;
}, [cb]);

useEffect(() => {
const tick = () => savedCallback.current();
id.current = setTimeout(tick, delay);
return () => clearId();
}, [delay]);

return clearId;
};
59 changes: 59 additions & 0 deletions packages/interactions/use-timeout/tests/use-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { renderHook } from '@testing-library/react';
import { useTimeout } from '../src';

describe('useTimeout test:', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('the timeout should work', () => {
const callback = jest.fn();
renderHook(() => useTimeout(callback, 1000));

expect(callback).not.toBeCalled();
jest.advanceTimersByTime(2000);
expect(callback).toHaveBeenCalledTimes(1);
});

it('should clear the timeout when the component unmounts', () => {
const callback = jest.fn();
const { unmount } = renderHook(() => useTimeout(callback, 1000));

expect(callback).not.toBeCalled();
unmount();
jest.advanceTimersByTime(2000);
expect(callback).not.toBeCalled();
});

it('should clear the timeout when the delay changes', () => {
const callback = jest.fn();
const { rerender } = renderHook(
({ delay }) => useTimeout(callback, delay),
{
initialProps: { delay: 1000 }
}
);

expect(callback).not.toBeCalled();
rerender({ delay: 2000 });
jest.advanceTimersByTime(1000);
expect(callback).not.toBeCalled();
jest.advanceTimersByTime(4000);
expect(callback).toHaveBeenCalledTimes(1);
});

it('should stop the timeout when the clear function is called', () => {
const callback = jest.fn();
const { result } = renderHook(() => useTimeout(callback, 4000));

expect(callback).not.toBeCalled();
jest.advanceTimersByTime(2000);
result.current();
jest.advanceTimersByTime(2000);
expect(callback).not.toBeCalled();
});
});
27 changes: 14 additions & 13 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 743dd1e

Please sign in to comment.