Skip to content
Merged
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
1 change: 1 addition & 0 deletions packages/tiny-react-hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './useDisclosure';
export * from './useStableCallback';
1 change: 1 addition & 0 deletions packages/tiny-react-hooks/src/useStableCallback/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useStableCallback';
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useStableCallback } from './useStableCallback';

interface Props {
count: number;
}

export default function Component({
count,
}: Props) {
const sum = useStableCallback(() => {
console.log(count * 10);
});

return <button type="button" role="button" onClick={sum}>Click me and see the console</button>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A hook that keep the callback always stable and do not need to add to dependencies of other hooks
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { renderHook } from '@testing-library/react';

import { useStableCallback } from './useStableCallback';

describe('useStableCallback()', () => {
it('should return the callback', () => {
const mockFn = vi.fn(() => 1);
const { result } = renderHook(() => useStableCallback(mockFn));

expect(result.current()).toBe(1);
expect(typeof result.current).toBe('function');
});

describe('when fn is changed', () => {
it('should return the correct callback', () => {
const mockFn1 = vi.fn(() => 1);
const mockFn2 = vi.fn(() => 2);
const { result, rerender } = renderHook(
({ fn }) => useStableCallback(fn),
{ initialProps: { fn: mockFn1 } },
);
expect(result.current()).toBe(1);
rerender({ fn: mockFn2 });
expect(result.current()).toBe(2);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useEffect, useMemo, useRef } from 'react';

/** Hook return type */
type UseStableCallbackReturnType<T extends (...args: unknown[]) => unknown> = T;

/**
* Custom hook that ...
* @param {Function} [fn] - your function need to be stable
* @returns {UseStableCallbackReturnType} return the the stable callback that will apply the newest function
* @public
* @example
* ```tsx
* const stableFn = useStableCallback((a: number, b: number) => {
* return a + b;
* });
*
* console.log(stableFn(1, 2)); // 3
* ```
*/
export function useStableCallback<T extends (...args: unknown[]) => unknown>(
fn: T,
): UseStableCallbackReturnType<T> {
const callbackRef = useRef<T>(fn);

useEffect(() => {
callbackRef.current = fn;
}, [fn]);

return useMemo(() => ((...args) => callbackRef.current(...args)) as T, []);
}