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-safe-async-mount

v1.0.1

Published

<!-- markdownlint-disable MD033 MD041 -->

Downloads

1

Readme

use-safe-async-mountThe Asynchronous Functional Component Mounter

The Problem

This is a useEffect hook with zero dependencies:

useEffect(() => {
  // Code that runs "on mount" (unfortunately)
}, [])

It is the most incorrectly [and dangerously] used part of the react functional component lifecycle.

Whenever using this hook (with the empty dependency array), you should ask yourself two questions:

  1. Am I using this to just initialize a variable based on some synchronously computed value?

    • useEffect(() => { setValue(computeMyValue()) }, [])
  2. Am I using this to just conditionally initialize a state variable based on props?

    • useEffect(() => { setValue(someProp ? "a" : "b") }, [])

If either of these situations describes you, there's a high chance you should be just be computing the value in-line or using useMemo. This saves you from having to deal with the initial render when your value (useState, useRef, var, etc.) is undefined.

Here's some situations that do fit in the empty useEffect hook:

  • Making a network request
  • Setting/removing an event listener
  • UI-related analytics tracking

Async State

When a component's state depends on a value gathered from an async function, the common solution is to manually invoke it directly from the empty useEffect hook:

The Traditional Pattern

function ExampleComponent() {
  const [stateOne, setStateOne] = useState()

  useEffect(() => {
    someAsyncFunction().then(res => setStateOne(res))
    // OR
    const run = async () => {
      const res = await someAsyncFunction()
      setStateOne(res)
    }
    run();
  }, [])

  return (
    <>
        <h1>My Example Component</h1>
        {stateOne && <p>{stateOne}</p>}
    </>
  )
}

The Drawbacks

There's three negative implications to this solution:

  1. When the component initially mounts, the variable is undefined. This requires more render logic.
  2. The component may unmount during the asynchronous request. Setting a state variable on an unmounted component is a memory leak and will throw an error.
  3. In TypeScript projects, your compiler won't recognize that your variable has been defined. That means !'s everywhere.

The Solution

Installation

npm i use-safe-async-mount

use-safe-async-mount solves these problems by acting as a true hook-based, type-safe componentWillMount implementation.

Example

import useSafeAsyncMount from 'use-safe-async-mount';

function ExampleComponent() {

  const { SafeRender } = useSafeAsyncMount(async isActive => {
    const res = await someAsyncFunction()
    if (isActive()) {
      // ^ This avoids setting component state after unmount
      
      // These values are defined and type-safe in the `SafeRender` component
      return { 
        stateOne: "Some value my component depends on",
        stateTwo: res
      }
    }
  })

  return (
    <>
      <h1>My Example Component</h1>
      <SafeRender>
        {({ stateOne, stateTwo }) => (
          <p>{stateOne}</p>
        )}
      </SafeRender>
    </>
  )
}

Example

Here's an interactive example and the associated source code.

Inspirations