useVisibleKey.ts20 lines · main
1import { useState } from 'react'
2
3/**
4 * Returns a key that increments each time `isVisible` transitions from false to true.
5 * Use this as the `key` prop on a component to force a clean remount on each open,
6 * instead of a `useEffect` that imperatively resets internal state.
7 */
8export function useVisibleKey(isVisible: boolean): number {
9 const [key, setKey] = useState(0)
10 const [prevIsVisible, setPrevIsVisible] = useState(false)
11
12 if (isVisible && !prevIsVisible) {
13 setPrevIsVisible(true)
14 setKey((k) => k + 1)
15 } else if (!isVisible && prevIsVisible) {
16 setPrevIsVisible(false)
17 }
18
19 return key
20}