Skip to content

Commit 4925f8a

Browse files
committed
fix(store): switch useMemo to useRef for local stores
1 parent 1f4aa86 commit 4925f8a

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/store.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useMemo } from 'react';
1+
import { useRef } from 'react';
22
import { observable } from '@nx-js/observer-util';
33

44
import {
@@ -12,7 +12,13 @@ export function store(obj) {
1212
// if it is a local store in a function component
1313
// create a memoized store at the first call instead
1414
if (isInsideFunctionComponent) {
15-
return useMemo(() => observable(obj), []);
15+
// we have to use useRef instead of useMemo for local store persistence
16+
// useMemo does not have the same guarantees about persistence as refs
17+
// see this docs for more explanation: https://reactjs.org/docs/hooks-reference.html#usememo
18+
const ref = useRef(obj);
19+
// observable wrapping is idempotent
20+
// wrapping the same object multiple times is the same as wrapping it once
21+
return observable(ref.current);
1622
}
1723
if (isInsideFunctionComponentWithoutHooks) {
1824
throw new Error(

0 commit comments

Comments
 (0)