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
15 changes: 14 additions & 1 deletion src/hooks/useEffectState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,28 @@ type NotifyEffectUpdate = (callback: UpdateCallbackFunc) => void;
export function useBatcher() {
// Updater Trigger
const updateFuncRef = React.useRef<UpdateCallbackFunc[]>(null);
const destroyedRef = React.useRef(false);

React.useEffect(() => {
destroyedRef.current = false;
return () => {
destroyedRef.current = true;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
updateFuncRef.current = null;
};
}, []);

// Notify update
const notifyEffectUpdate: NotifyEffectUpdate = callback => {
if (destroyedRef.current) {
return;
}

if (!updateFuncRef.current) {
updateFuncRef.current = [];

channelUpdate(() => {
unstable_batchedUpdates(() => {
updateFuncRef.current.forEach(fn => {
updateFuncRef.current?.forEach(fn => {
fn();
});
updateFuncRef.current = null;
Expand Down
39 changes: 39 additions & 0 deletions tests/useEffectState.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { act, renderHook } from '@testing-library/react';
import { useBatcher } from '../src/hooks/useEffectState';

describe('useEffectState / useBatcher', () => {
it('should process updates after StrictMode re-establishes effects', async () => {
const callback = jest.fn();
const { result } = renderHook(() => useBatcher(), {
reactStrictMode: true,
});

result.current(callback);

await act(async () => {
await new Promise(resolve => setTimeout(resolve, 50));
});

expect(callback).toHaveBeenCalledTimes(1);
});

it('should clean up queued updates on unmount', async () => {
let notify: any;
let updateCalled = false;
const { unmount } = renderHook(() => {
notify = useBatcher();
});

notify(() => {
updateCalled = true;
});

unmount();

await act(async () => {
await new Promise(resolve => setTimeout(resolve, 50));
});

expect(updateCalled).toBe(false);
});
});