diff --git a/src/internal/singleton-handler/__tests__/create-singleton-state.test.tsx b/src/internal/singleton-handler/__tests__/create-singleton-state.test.tsx
index 37c1329..ee589d5 100644
--- a/src/internal/singleton-handler/__tests__/create-singleton-state.test.tsx
+++ b/src/internal/singleton-handler/__tests__/create-singleton-state.test.tsx
@@ -7,13 +7,17 @@ import { createSingletonState } from '../index';
function setup() {
const state = {
+ value: 0,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
handler: (value: number) => {},
};
const useSingletonState = createSingletonState({
- initialState: 0,
+ initialState: () => state.value,
factory: handler => {
- state.handler = handler;
+ state.handler = value => {
+ handler(value);
+ state.value = value;
+ };
return () => {};
},
});
@@ -62,3 +66,16 @@ test('should use updated value for late-rendered components', () => {
expect(container).toHaveTextContent('first: 123');
expect(container).toHaveTextContent('second: 123');
});
+
+test('should use latest value from the global state', () => {
+ const { Demo, state } = setup();
+ const { container, rerender } = render();
+ expect(container).toHaveTextContent('first: 0');
+ state.handler(123);
+ expect(container).toHaveTextContent('first: 123');
+ rerender(<>>);
+ // value changes when there are no active listeners
+ state.value = 456;
+ rerender();
+ expect(container).toHaveTextContent('first: 456');
+});
diff --git a/src/internal/singleton-handler/index.ts b/src/internal/singleton-handler/index.ts
index 0ac85a3..3c6bd75 100644
--- a/src/internal/singleton-handler/index.ts
+++ b/src/internal/singleton-handler/index.ts
@@ -46,13 +46,9 @@ interface SingletonStateOptions {
export function createSingletonState({ factory, initialState }: SingletonStateOptions) {
const useSingleton = createSingletonHandler(factory);
- let value = initialState;
return function useSingletonState() {
- const [state, setState] = useState(value);
- useSingleton(newValue => {
- value = newValue;
- setState(newValue);
- });
+ const [state, setState] = useState(initialState);
+ useSingleton(setState);
return state;
};
}