diff --git a/src/workspaces/hooks/src/useSessionState.ts b/src/workspaces/hooks/src/useSessionState.ts index 5fcf7053..1b561faa 100644 --- a/src/workspaces/hooks/src/useSessionState.ts +++ b/src/workspaces/hooks/src/useSessionState.ts @@ -76,6 +76,8 @@ export function useSessionState(key: string, initialValue: T) { valueRef.current = value; const setGlobalRef = useRef(setGlobal); setGlobalRef.current = setGlobal; + const initialValueRef = useRef(initialValue); + initialValueRef.current = initialValue; const setValue = useCallback( (arg: React.SetStateAction) => { @@ -86,11 +88,11 @@ export function useSessionState(key: string, initialValue: T) { [key], ); + // Read through the ref, not the closure: resetting means "whatever the default is now", and a + // `useCallback` over `initialValue` would freeze the default from the render that built the callback. const reset = useCallback(() => { clearSessionValue(key); - setGlobalRef.current(initialValue); - // `initialValue` is read at reset time on purpose: resetting means "whatever the default is now". - // eslint-disable-next-line react-hooks/exhaustive-deps + setGlobalRef.current(initialValueRef.current); }, [key]); return [value, setValue, reset] as const;