useVisibleKey.ts 620 B

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