useAbortController – A React Hook to work with the AbortController

Kent C. Dodds recently floated this snippet around, a React Hook to easily work with the the AbortController:


function useAbortController() {
  const abortControllerRef = React.useRef()
  const getAbortController = React.useCallback(() => {
    if (!abortControllerRef.current) {
      abortControllerRef.current = new AbortController()
    }
    return abortControllerRef.current
  }, [])

  React.useEffect(() => {
    return () => getAbortController().abort()
  }, [getAbortController])

  const getSignal = React.useCallback(() => getAbortController().signal, [
    getAbortController,
  ])

  return getSignal;
}

💁‍♂️ The AbortController is a Web API which allows you to cancel JavaScript promises.

useSound – A React Hook for Sound Effects

Josh W. Comeau:

Because sound is used so rarely on the web, it can be quite impactful. It’s a bit of a secret weapon, and it can make a surprisingly big difference for the right kinds of projects!

To make it a bit easier to get started, I pulled out the hook I built for this blog, use-sound, and published it on NPM.

import useSound from 'use-sound';

import boopSfx from '../../sounds/boop.mp3';

const BoopButton = () => {
  const [play] = useSound(boopSfx);

  return <button onClick={play}>Boop!</button>;
};

Installation per NPM/Yarn.

yarn add use-sound

Built on top of the wonderful Howler.js

useSound – A React Hook for Sound Effects →
Beep Boop! Announcing “use-sound” →

useDimensions – a React Hook to measure DOM nodes

import React from 'react'
import useDimensions from 'react-use-dimensions'

const MeasuredNode = () => {
    const [ref, { x, y, width, height }] = useDimensions();

    return (
        <p ref={ref}>
            I am a paragraph at ({x}px, {y}px) position with a width of {width}px
            and height of {height}px
        </p>
    );
};

Handy. Uses window.resize+window.scroll internally, yet I’m quite sure it could be done using the more modern ResizeObserver+IntersectionObserver too.

useDimensions demo →
useDimensions Source (GitHub) →