From 0a7f461d392dbf887ab562e38a2e827e124bfa80 Mon Sep 17 00:00:00 2001 From: Tae Hyung Kim Date: Wed, 7 May 2025 12:57:19 -0700 Subject: Fix flicker in iterm2 (#266) --- packages/cli/src/ui/hooks/useStateAndRef.ts | 36 +++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 packages/cli/src/ui/hooks/useStateAndRef.ts (limited to 'packages/cli/src/ui/hooks/useStateAndRef.ts') diff --git a/packages/cli/src/ui/hooks/useStateAndRef.ts b/packages/cli/src/ui/hooks/useStateAndRef.ts new file mode 100644 index 00000000..d073a1dc --- /dev/null +++ b/packages/cli/src/ui/hooks/useStateAndRef.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import React from 'react'; + +// Hook to return state, state setter, and ref to most up-to-date value of state. +// We need this in order to setState and reference the updated state multiple +// times in the same function. +export const useStateAndRef = < + // Everything but function. + T extends object | null | undefined | number | string, +>( + initialValue: T, +) => { + const [_, setState] = React.useState(initialValue); + const ref = React.useRef(initialValue); + + const setStateInternal = React.useCallback( + (newStateOrCallback) => { + let newValue: T; + if (typeof newStateOrCallback === 'function') { + newValue = newStateOrCallback(ref.current); + } else { + newValue = newStateOrCallback; + } + setState(newValue); + ref.current = newValue; + }, + [], + ); + + return [ref, setStateInternal] as const; +}; -- cgit v1.2.3