File tree Expand file tree Collapse file tree 1 file changed +24
-7
lines changed
Expand file tree Collapse file tree 1 file changed +24
-7
lines changed Original file line number Diff line number Diff line change @@ -26,18 +26,35 @@ export function useStateStore<
2626 ) ;
2727
2828 const wrappedSnapshot = useMemo ( ( ) => {
29- let cached : [ T , O ] ;
29+ let cachedTuple : [ T , O ] ;
30+
3031 return ( ) => {
31- const current = store ?. getLatestValue ( ) ;
32+ const currentValue = store ?. getLatestValue ( ) ;
33+
34+ if ( ! currentValue ) return undefined ;
35+
36+ // store value hasn't changed, no need to compare individual values
37+ if ( cachedTuple && cachedTuple [ 0 ] === currentValue ) {
38+ return cachedTuple [ 1 ] ;
39+ }
40+
41+ const newlySelected = selector ( currentValue ) ;
42+
43+ // store value changed but selected values wouldn't have to, double-check selected
44+ if ( cachedTuple ) {
45+ let selectededAreEqualToCached = true ;
3246
33- if ( ! current ) return undefined ;
47+ for ( const key in cachedTuple [ 1 ] ) {
48+ if ( cachedTuple [ 1 ] [ key ] === newlySelected [ key ] ) continue ;
49+ selectededAreEqualToCached = false ;
50+ break ;
51+ }
3452
35- if ( ! cached || cached [ 0 ] !== current ) {
36- cached = [ current , selector ( current ) ] ;
37- return cached [ 1 ] ;
53+ if ( selectededAreEqualToCached ) return cachedTuple [ 1 ] ;
3854 }
3955
40- return cached [ 1 ] ;
56+ cachedTuple = [ currentValue , newlySelected ] ;
57+ return cachedTuple [ 1 ] ;
4158 } ;
4259 } , [ store , selector ] ) ;
4360
You can’t perform that action at this time.
0 commit comments