MCPcopy
hub / github.com/pmndrs/jotai / useAtomValue

Function useAtomValue

src/react/useAtomValue.ts:120–206  ·  view source on GitHub ↗
(atom: Atom<Value>, options?: Options)

Source from the content-addressed store, hash-verified

118): Awaited<ExtractAtomValue<AtomType>>
119
120export 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
165Migration guide:
166
167Create a custom hook like the following.
168
169function 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, () => {

Callers 15

useAtomFunction · 0.90
ComponentFunction · 0.90
DisplayerFunction · 0.90
CounterFunction · 0.90
AppFunction · 0.90
ComponentFunction · 0.90
CountFunction · 0.90
ComponentFunction · 0.90
CounterFunction · 0.90
AsyncComponentFunction · 0.90
ErrorComponentFunction · 0.90
ObjComponentFunction · 0.90

Calls 4

useStoreFunction · 0.90
attachPromiseStatusFunction · 0.85
createContinuablePromiseFunction · 0.85
isPromiseLikeFunction · 0.70

Tested by 15

ComponentFunction · 0.72
DisplayerFunction · 0.72
CounterFunction · 0.72
AppFunction · 0.72
ComponentFunction · 0.72
CountFunction · 0.72
ComponentFunction · 0.72
CounterFunction · 0.72
AsyncComponentFunction · 0.72
ErrorComponentFunction · 0.72
ObjComponentFunction · 0.72
ResolveAtomComponentFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…