Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/useRafCallback/index.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,37 @@ describe('useRafCallback', () => {

expect(spy).not.toHaveBeenCalled();
});
it('should cancel a frame scheduled from inside the callback', async () => {
const spy = vi.fn(() => {
if (spy.mock.calls.length === 1) {
value[0]();
}
});
const {result} = await renderHook(() => useRafCallback(spy));
const value = expectResultValue(result);

value[0]();
vi.advanceTimersToNextTimer();
expect(spy).toHaveBeenCalledTimes(1);

value[1]();
vi.runAllTimers();
expect(spy).toHaveBeenCalledTimes(1);
});

it('should cancel a reentrant frame on unmount', async () => {
const spy = vi.fn(() => {
if (spy.mock.calls.length === 1) {
value[0]();
}
});
const {result, unmount} = await renderHook(() => useRafCallback(spy));
const value = expectResultValue(result);

value[0]();
vi.advanceTimersToNextTimer();
await unmount();
vi.runAllTimers();
expect(spy).toHaveBeenCalledTimes(1);
});
});
2 changes: 1 addition & 1 deletion src/useRafCallback/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ export function useRafCallback<T extends (...args: any[]) => any>(
cancel();

frame.current = requestAnimationFrame(() => {
cbRef.current(...args);
frame.current = 0;
cbRef.current(...args);
});
};

Expand Down