npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-presence

v1.3.0

Published

A lightweight React hook to animate the presence of an element.

Downloads

12,383

Readme

use-presence

Stable release

A 1kb React hook to animate the presence of an element.

Demo app

The problem

There are two problems that you have to solve when animating the presence of an element:

  1. During enter animations, you have to render an initial state where the element is hidden and only after this has flushed to the DOM, you can can animate the final state that the element should animate towards.
  2. Exit animations are a bit tricky in React, since this typically means that a component unmounts. However when the component has already unmounted, you can't animate it anymore. A workaround is often to keep the element mounted, but that keeps unnecessary elements around and can hurt accessibility, as hidden interactive elements might still be focusable.

This solution

This hook provides a lightweight solution where the animating element is only mounted the minimum of time, while making sure the animation is fully visible to the user. The rendering is left to the user to support all kinds of styling solutions.

Example

import usePresence from 'use-presence';

function Expander({children, isOpen, transitionDuration = 500}) {
  const {isMounted, isVisible, isAnimating} = usePresence(isOpen, {transitionDuration});

  if (!isMounted) {
    return null;
  }
  
  return (
    <div style={{
      overflow: 'hidden',
      maxHeight: 0,
      opacity: 0,
      transitionDuration: `${transitionDuration}ms`,
      transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
      transitionProperty: 'max-height, opacity',
      ...(isVisible && {
        maxHeight: 500,
        opacity: 1,
        transitionTimingFunction: 'cubic-bezier(0.8, 0, 0.6, 1)'
      }),
      ...(isAnimating && {willChange: 'max-height, opacity'})
    }}>
      {children}
    </div>
  );
}

API

const {
  /** Should the component be returned from render? */
  isMounted,
  /** Should the component have its visible styles applied? */
  isVisible,
  /** Is the component either entering or exiting currently? */
  isAnimating,
  /** Is the component entering currently? */
  isEntering,
  /** Is the component exiting currently? */
  isExiting
} = usePresence(
  /** Indicates whether the component that the resulting values will be used upon should be visible to the user. */
  isVisible: boolean,
  opts: {
    /** Duration in milliseconds used both for enter and exit transitions. */
    transitionDuration: number;
    /** Duration in milliseconds used for enter transitions (overrides `transitionDuration` if provided). */
    enterTransitionDuration: number;
    /** Duration in milliseconds used for exit transitions (overrides `transitionDuration` if provided). */
    exitTransitionDuration: number;
    /** Opt-in to animating the entering of an element if `isVisible` is `true` during the initial mount. */
    initialEnter?: boolean;
  }
)

usePresenceSwitch

If you have multiple items where only one is visible at a time, you can use the supplemental usePresenceSwitch hook to animate the items in and out. Previous items will exit before the next item transitions in.

API

const {
  /** The item that should currently be rendered. */
  mountedItem,
  /** Returns all other properties from `usePresence`. */
  ...rest
} = usePresence<ItemType>(
  /** The current item that should be visible. If `undefined` is passed, the previous item will animate out. */
  item: ItemType | undefined,
  /** See the `opts` argument of `usePresence`. */
  opts: Parameters<typeof usePresence>[1]
)

Example

const tabs = [
  {
    title: 'Tab 1',
    content: 'Tab 1 content'
  },
  {
    title: 'Tab 2',
    content: 'Tab 2 content'
  },
  {
    title: 'Tab 3',
    content: 'Tab 3 content'
  },
];

function Tabs() {
  const [tabIndex, setTabIndex] = useState(0);

  return (
    <>
      {tabs.map((tab, index) => (
        <button key={index} onClick={() => setTabIndex(index)} type="button">
          {tab.title}
        </button>
      ))}
      <TabContent>
        {tabs[tabIndex].content}
      </TabContent>
    </>
  );
}

function TabContent({ children, transitionDuration = 500 }) {
  const {
    isMounted,
    isVisible,
    mountedItem,
  } = usePresenceSwitch(children, { transitionDuration });

  if (!isMounted) {
    return null;
  }

  return (
    <div
      style={{
        opacity: 0,
        transitionDuration: `${transitionDuration}ms`,
        transitionProperty: 'opacity',
        ...(isVisible && {
          opacity: 1
        })
      }}
    >
      {mountedItem}
    </div>
  );
}

Related