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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [`prettier@3.3.3`](https://npmjs.com/package/prettier/v/3.3.3)
- [`tsup@8.3.0`](https://npmjs.com/package/tsup/v/8.3.0)
- [`typescript@5.6.3`](https://npmjs.com/package/typescript/v/5.6.3)
- Fixed `usePropagate` hook to return a stable function reference across re-renders, in PR [#23](https://github.com/compulim/use-propagate/pull/23), by [@OEvgeny](https://github.com/OEvgeny)

## [0.2.0] - 2024-07-24

Expand Down
26 changes: 26 additions & 0 deletions packages/use-propagate/src/private/createPropagation.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,32 @@ describe('A propagation', () => {
// Listener should not be called as the component is unmounted
expect(listener).not.toHaveBeenCalled();
});

test('usePropagate should return stable function reference', () => {
const propagateRefs: Array<(value: number) => void> = [];

const Component = () => {
const propagate = usePropagate();
propagateRefs.push(propagate);
return null;
};

const { rerender } = render(
<PropagationScope>
<Component />
</PropagationScope>
);

// Force re-render
rerender(
<PropagationScope>
<Component />
</PropagationScope>
);

// The function reference should be stable across re-renders
expect(propagateRefs[0]).toBe(propagateRefs[1]);
});
});
});

Expand Down
30 changes: 21 additions & 9 deletions packages/use-propagate/src/private/createPropagation.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import React, { createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, type ReactNode } from 'react';
import React, {
createContext,
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
type ReactNode
} from 'react';
import { useRefFrom } from 'use-ref-from';
import createPropagationContextValue, {
type Listener,
Expand Down Expand Up @@ -52,15 +61,18 @@ export default function createPropagation<T>(init: Init = {}) {
rendering = false;
});

return (value: T) => {
if (rendering && !allowPropagateDuringRender) {
return console.warn(
'use-propagate: The propagate callback function should not be called while rendering, ignoring the call.'
);
}
return useCallback(
(value: T) => {
if (rendering && !allowPropagateDuringRender) {
return console.warn(
'use-propagate: The propagate callback function should not be called while rendering, ignoring the call.'
);
}

runListeners(value);
};
runListeners(value);
},
[runListeners]
);
}
};
}