Skip to content

Commit

Permalink
feat(useRafLoop): implement #1090
Browse files Browse the repository at this point in the history
  • Loading branch information
xobotyi committed Apr 1, 2020
1 parent 1653a6d commit 1ef1272
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/useRafLoop.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ const Demo = () => {
```ts
const [stopLoop, isActive, startLoop] = useRafLoop(callback: CallableFunction, deps?: DependencyList);
```
* `callback` — function to call each RAF tick
* `callback(time: number)` — function to call each RAF tick

5 changes: 2 additions & 3 deletions src/useRafLoop.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable */
import { useEffect, useRef, useState } from 'react';

export type RafLoopReturns = [() => void, boolean, () => void];
Expand All @@ -7,8 +6,8 @@ export default function useRafLoop(callback: CallableFunction): RafLoopReturns {
const raf = useRef<number | null>(null);
const [isActive, setIsActive] = useState<boolean>(true);

function loopStep() {
callback();
function loopStep(time: number) {
callback(time);
raf.current = requestAnimationFrame(loopStep);
}

Expand Down
16 changes: 16 additions & 0 deletions tests/useRafLoop.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,20 @@ describe('useRafLoop', () => {

expect(spy).not.toBeCalled();
});

it('should pass timestamp as 1st argument of callback', () => {
const spy = jest.fn();
const hook = renderHook(() => useRafLoop(spy), { initialProps: false });

requestAnimationFrame.step();

act(() => {
hook.result.current[0]();
});

requestAnimationFrame.step();

expect(spy).toHaveBeenCalled();
expect(typeof spy.mock.calls[0][0]).toBe('number');
});
});

0 comments on commit 1ef1272

Please sign in to comment.