(atom: Atom<Value>, options?: Options)
| 118 | ): Awaited<ExtractAtomValue<AtomType>> |
| 119 | |
| 120 | export function useAtomValue<Value>(atom: Atom<Value>, options?: Options) { |
| 121 | const { delay, unstable_promiseStatus: promiseStatus = !React.use } = |
| 122 | options || {} |
| 123 | const store = useStore(options) |
| 124 | |
| 125 | const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] = |
| 126 | useReducer<readonly [Value, Store, typeof atom], undefined, []>( |
| 127 | (prev) => { |
| 128 | const nextValue = store.get(atom) |
| 129 | if ( |
| 130 | Object.is(prev[0], nextValue) && |
| 131 | prev[1] === store && |
| 132 | prev[2] === atom |
| 133 | ) { |
| 134 | return prev |
| 135 | } |
| 136 | return [nextValue, store, atom] |
| 137 | }, |
| 138 | undefined, |
| 139 | () => [store.get(atom), store, atom], |
| 140 | ) |
| 141 | |
| 142 | let value = valueFromReducer |
| 143 | if (storeFromReducer !== store || atomFromReducer !== atom) { |
| 144 | rerender() |
| 145 | value = store.get(atom) |
| 146 | } |
| 147 | |
| 148 | useEffect(() => { |
| 149 | const unsub = store.sub(atom, () => { |
| 150 | if (promiseStatus) { |
| 151 | try { |
| 152 | const value = store.get(atom) |
| 153 | if (isPromiseLike(value)) { |
| 154 | attachPromiseStatus( |
| 155 | createContinuablePromise(store, value, () => store.get(atom)), |
| 156 | ) |
| 157 | } |
| 158 | } catch { |
| 159 | // ignore |
| 160 | } |
| 161 | } |
| 162 | if (typeof delay === 'number') { |
| 163 | console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3. |
| 164 | |
| 165 | Migration guide: |
| 166 | |
| 167 | Create a custom hook like the following. |
| 168 | |
| 169 | function useAtomValueWithDelay<Value>( |
| 170 | atom: Atom<Value>, |
| 171 | options: { delay: number }, |
| 172 | ): Value { |
| 173 | const { delay } = options |
| 174 | const store = useStore(options) |
| 175 | const [value, setValue] = useState(() => store.get(atom)) |
| 176 | useEffect(() => { |
| 177 | const unsub = store.sub(atom, () => { |
searching dependent graphs…