diff options
| author | Tae Hyung Kim <[email protected]> | 2025-05-07 12:57:19 -0700 |
|---|---|---|
| committer | GitHub <[email protected]> | 2025-05-07 12:57:19 -0700 |
| commit | 0a7f461d392dbf887ab562e38a2e827e124bfa80 (patch) | |
| tree | cb0c70da1fbd57630da59c14b69c5f7ea9d1d92b /packages/cli/src/ui/hooks/useStateAndRef.ts | |
| parent | 358281f0fda7ef4045ca2e9d827a45b56f949467 (diff) | |
Fix flicker in iterm2 (#266)
Diffstat (limited to 'packages/cli/src/ui/hooks/useStateAndRef.ts')
| -rw-r--r-- | packages/cli/src/ui/hooks/useStateAndRef.ts | 36 |
1 files changed, 36 insertions, 0 deletions
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<T>(initialValue); + const ref = React.useRef<T>(initialValue); + + const setStateInternal = React.useCallback<typeof setState>( + (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; +}; |
