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

react-callback-after-paint-ts

v1.1.3

Published

React hook that runs a sideEffect when the next frame has been painted by the browser

Downloads

283

Readme

react-callback-after-paint

Table of contents

  1. Changelog
  2. Introduction
  3. Credits
  4. How this hook works

Changelog

Version 1.0.0 > 1.1.0

    1. Add optional argument dependencies, and unpack in useEffect dependencies array - [markName, enabled, ...dependencies]
    2. Re-run your side-effects whenever dependencies change

1.0.0 > 1.1.1

    1. Update README and CHANGELOG
    2. Introducing new argument - dependencies

Introduction

Hi my name is Jean, I am a React developer, I encountered a bug re race-condition rendering, wherein two components render side by side, one referencing the other, but the latter could take a bit long to render depending on network conditions and main-thread load.

I absolutely had to find away to run a sideEffect when my target (the latter) component has been painted on screen, I always thought a useEffect hook would run after a component was painted on the screen, but that it not quite the case, I discovered sometimes it does, sometimes it does not, I will include useful links that describe the problem in more detail.

Detecting when the Browser Paints Frames in JavaScript Detecting when React Components are Visually Rendered as Pixels


Credits

Big thank you to Joe Liccini, all credits go to Joe, I am publishing this package to help others, I may adapt and improve in future releases, you can see the original inspiration https://webperf.tips/tip/react-hook-paint/, authored by Joe Liccini!.

How this hook works

We can utilize the requestAnimationFrame and MessageChannel APIs to more accurately log when a DOM update is represented visually to the user.

To do this, we will use the following helper function:

/**
* Runs `callback` shortly after the next browser Frame is produced.
*/
function runAfterFramePaint(callback) {
    requestAnimationFrame(() => {
        const messageChannel = new MessageChannel();

        messageChannel.port1.onmessage = callback;
        messageChannel.port2.postMessage(undefined);
    });
}

Note: In production code, we would need to adjust this callback to account for cases where the document.visibilityState is hidden and requestAnimationFrame won't fire. Production code would also need to handle cancellation if the React component is unmounted before this fires.

With our new helper setup, we can integrate it into a re-usable React Hook:

function useCallbackAfterPaint({ markName, enabled, cb, dependencies = [] }) {
    useEffect(() => {
        if (!enabled) {
            return;
        }
        // Queues a requestAnimationFrame and onmessage
        runAfterFramePaint(() => {
            // Set a performance mark shortly after the frame has been produced.
            performance.mark((markName !== null && markName !== void 0 ? markName : "MyPerformanceMark"));
            if (cb)
                cb();
        });
}, [markName, enabled, ...dependencies]);

In your Component, we can use this hook like this:

function MyComponent(props) {
    useMarkFramePaint({
        markName: 'MyComponentRendered',
        /**
        * Signal to the hook that we want to capture the frame right after our item list
        * model is populated.
        */
        enabled: !!props.items?.length,
        cb: () => window.alert("I am a callback!"),
        dependencies: [ <someState> ]
    });

    return (
        <ul>
            {
                props.items?.map(item => (
                    <li key={item.id}>{item.text}</li>
                ))
            }
        </ul>
    );
}

With this hook integrated, we will queue a performance.mark() operation when props.items is populated. It will execute on the next frame produced after React JavaScript task completes:

Rendering Illustration