Skip to content

pacocoursey/use-delayed-render

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
May 13, 2020

useDelayedRender npm bundle size

useDelayedRender is a react hook for delaying the render and unmount of a component. This is commonly used to animate UI on unmount.


Installation

$ yarn add use-delayed-render

Usage

Function signature:

const { mounted: boolean, rendered: boolean } = useDelayedRender(
  active: boolean,
  options?: {
    enterDelay: number,
    exitDelay: number,
    onUnmount: () => void
  }
)

Options:

  • active: Whether your component is in an active state
  • enterDelay: After mounting, the delay before rendered becomes true
  • exitDelay: After rendered becomes false, the delay before unmounting
  • onUnmount: A callback triggered after unmounting

Return values:

  • mounted: Whether your component should be mounted in the DOM
  • rendered: Whether your component should be visible

Example

Render a modal, but delay the unmount so that our 2 second CSS transition completes before the modal is removed from the DOM.

const Modal = ({ active }) => {
  const { mounted, rendered } = useDelayedRender(active, {
    exitDelay: 2000,
  })

  if (!mounted) return null

  return (
    <Portal>
      <div className={rendered ? 'modal visible' : 'modal'}>{/* ... */}</div>
    </Portal>
  )
}

This allows you to use simple CSS transitions to animate the mounting/unmounting of your component.

.modal {
  opacity: 0;
  transition: opacity 2s ease;
}

.modal.visible {
  opacity: 1;
}

Why?

  • Usually you would use react-transition-group to solve this, but the 2.37MB install size is a bit overkill, compared to this package at 491B gzipped.
<Transition in={active} unmountOnExit timeout={200} onExited={handleExit}>
  <Modal />
</Transition>
  • Hooks solve the problem without needing a render function or HOC.

About

react hook for delaying the render and unmount of a component

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published