( store: Readable<TSnapshot>, selector?: (snapshot: TSnapshot) => T, compare: (a: T | undefined, b: T) => boolean = defaultCompare )
| 150 | compare?: (a: TSnapshot | undefined, b: TSnapshot | undefined) => boolean |
| 151 | ): TSnapshot; |
| 152 | export function useSelector<TSnapshot, T>( |
| 153 | store: Readable<TSnapshot>, |
| 154 | selector?: (snapshot: TSnapshot) => T, |
| 155 | compare: (a: T | undefined, b: T) => boolean = defaultCompare |
| 156 | ): T | TSnapshot { |
| 157 | const subscribe = useCallback( |
| 158 | (handleStoreChange: () => void) => |
| 159 | store.subscribe(handleStoreChange).unsubscribe, |
| 160 | [store] |
| 161 | ); |
| 162 | |
| 163 | if (!selector) { |
| 164 | const selectorWithCompare = useSelectorWithCompare( |
| 165 | identity, |
| 166 | defaultCompare |
| 167 | ); |
| 168 | |
| 169 | return useSyncExternalStore( |
| 170 | subscribe, |
| 171 | () => selectorWithCompare(store.get()), |
| 172 | () => selectorWithCompare(store.get()) |
| 173 | ); |
| 174 | } |
| 175 | |
| 176 | const selectorWithCompare = useSelectorWithCompare(selector, compare); |
| 177 | |
| 178 | return useSyncExternalStore( |
| 179 | subscribe, |
| 180 | () => selectorWithCompare(store.get()), |
| 181 | () => selectorWithCompare(store.get()) |
| 182 | ); |
| 183 | } |
| 184 | |
| 185 | /** Creates a stable store instance for the lifetime of a React component. */ |
| 186 | export function useStore<TDefinition extends StoreDefinition>( |
searching dependent graphs…