Skip to content

Commit 9be2530

Browse files
committed
refactor: adjust token fetch options memoization calculation to use a ref instead of state
1 parent a6f22da commit 9be2530

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

packages/react/src/hooks/useSession.ts

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -196,42 +196,38 @@ function useSessionTokenSourceFetch(
196196
) {
197197
const isConfigurable = tokenSource instanceof TokenSourceConfigurable;
198198

199-
const [memoizedTokenFetchOptions, setMemoizedTokenFetchOptions] =
200-
React.useState<TokenSourceFetchOptions | null>(() => {
201-
if (isConfigurable) {
202-
return unstableRestOptions;
203-
} else {
204-
return null;
205-
}
206-
});
199+
const memoizedTokenFetchOptionsRef = React.useRef<TokenSourceFetchOptions | null>(
200+
isConfigurable ? unstableRestOptions : null,
201+
);
202+
207203
React.useEffect(() => {
208204
if (!isConfigurable) {
209-
setMemoizedTokenFetchOptions(null);
205+
memoizedTokenFetchOptionsRef.current = null;
210206
return;
211207
}
212208

213209
if (
214-
memoizedTokenFetchOptions !== null &&
215-
areTokenSourceFetchOptionsEqual(memoizedTokenFetchOptions, unstableRestOptions)
210+
memoizedTokenFetchOptionsRef.current !== null &&
211+
areTokenSourceFetchOptionsEqual(memoizedTokenFetchOptionsRef.current, unstableRestOptions)
216212
) {
217213
return;
218214
}
219215

220-
setMemoizedTokenFetchOptions(unstableRestOptions);
216+
memoizedTokenFetchOptionsRef.current = unstableRestOptions;
221217
}, [isConfigurable, unstableRestOptions]);
222218

223219
const tokenSourceFetch = React.useCallback(async () => {
224220
if (isConfigurable) {
225-
if (!memoizedTokenFetchOptions) {
221+
if (!memoizedTokenFetchOptionsRef.current) {
226222
throw new Error(
227223
`AgentSession - memoized token fetch options are not set, but the passed tokenSource was an instance of TokenSourceConfigurable. If you are seeing this please make a new GitHub issue!`,
228224
);
229225
}
230-
return tokenSource.fetch(memoizedTokenFetchOptions);
226+
return tokenSource.fetch(memoizedTokenFetchOptionsRef.current);
231227
} else {
232228
return tokenSource.fetch();
233229
}
234-
}, [isConfigurable, tokenSource, memoizedTokenFetchOptions]);
230+
}, [isConfigurable, tokenSource]);
235231

236232
return tokenSourceFetch;
237233
}

0 commit comments

Comments
 (0)