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

microhook

v1.7.0

Published

πŸ”₯πŸ”₯ Check out microhook! πŸš€ It's a lightweight library that makes it easy to use React hooks in your code. πŸ’»

Downloads

2

Readme

Build Status Code Coverage version downloads MIT License PRs Welcome

Watch on GitHub Star on GitHub

Table of Contents

Documentation

The latest usage documentation site is now available online! Explore our new documentation site here!

δΈ­ζ–‡η«™η‚Ήε·²η»ε‘εΈƒοΌŒη‚Ήε‡»ε‰εΎ€!

Introducing Hooks

Microhook is a lightweight React Hooks library that aims to provide some excellent custom Hooks to help developers improve development efficiency and code quality. πŸ’ͺ

Microhook's main features include:

πŸ‘‰ Simplicity and ease of use: The usage of each Hook is very simple and easy to understand, and the amount of code is very small.

πŸš€ High efficiency and practicality: Each Hook provided by Microhook is very practical and can be directly applied to projects, helping developers quickly solve some common problems.

πŸ’― Stable quality: Microhook has been fully tested and validated, and the code quality is guaranteed, so you can use it with confidence.

Microhook currently provides multiple Hooks, such as useLoading, usePortal, useRestHeight, etc. These Hooks can help you optimize your React projects, improve page performance and interaction experience. If you want to speed up your React development and improve your code quality, Microhook is definitely worth a try. 😎

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install microhook --save

or

for installation via yarn:

yarn add microhook

State

useLoading: Simplify Your Async Requests!

πŸ‘‹ Hey there! Let me introduce you to useLoading -- a custom React hook that makes handling the loading state of an API request or Promise a breeze. 🌬️

πŸ’» By utilizing useLoading, you can easily implement an elegant solution to handle asynchronous requests in your React application. With just a few lines of code, you can keep track of loading status and display a spinner or loading message to keep your users informed of the ongoing process. πŸš€

πŸ€” Still not sure how it works? Let's break it down:

  • A function that takes any number of arguments and returns a Promise.
  • An optional array of arguments.
  • An optional error type.

πŸŽ‰ The return value of useLoading is a tuple, containing two items:

An object with two properties, loading and data. loading is a boolean that indicates whether the request is currently being processed or not. data is an object containing the response data from the request.

An object with a single property, wrapRequest, which is an asynchronous function that wraps the original request and handles the loading state.

πŸ’‘ Here's a quick example of how to use useLoading in your code:

import { useLoading } from 'microhook';

async function fetchSomeData(arg1: string, arg2: number): Promise<{ message: string }> {
  // fetch data here...
}

function MyComponent() {
  const [response, { wrapRequset }] = useLoading(fetchSomeData);

  useEffect(() => {
    wrapRequset('some argument', 123);
  }, []);

  if (response.loading) {
    return <Spinner />;
  }

  return <div>{response.data?.message}</div>;
}

πŸŽ“ As you can see, useLoading simplifies handling the loading state and error handling of an API request or Promise, allowing you to focus on the core functionality of your application. Give it a try and let me know what you think! 🀩 For more information!

Side-effects

usePrefetch: Efficiently Prefetches External Resources!

πŸ‘‹ Hi there! Let me introduce you to usePrefetch, a React hook for prefetching resources like images, scripts, and stylesheets.

πŸ€” Why is it useful? By preloading resources, usePrefetch can improve perceived performance and reduce the likelihood of visible loading spinners or other loading indicators. This can make the app feel more responsive and improve the user experience.

To use it, first import it from your React component:

import { usePrefetch } from 'microhook';

Then, call the hook with an array of URLs and an optional options object:

const urls = ['https://example.com/image1.jpg', 'https://example.com/image2.jpg'];
const options = { type: 'link' };
usePrefetch(urls, options);

This will asynchronously fetch the resources and cache them for later use, improving your website's performance. 🏎️ For more information!

Interaction

useRestHeight: Calculate Remaining Height Dynamically!

πŸ‘‹ Hey there! Let me introduce you to useRestHeight, a React hook that calculates the remaining height of a container after subtracting the height of its child elements and any specified offsets.

πŸš€ This hook is perfect when you want to dynamically adjust the layout of a container based on its available height.

πŸ‘‰ To use this hook, simply import it from the corresponding module and call it inside a functional component with three arguments:

  • parent: A string or a React ref object that refers to the container element whose height you want to calculate.
  • children: An array of strings or React ref objects that refer to the child elements whose heights you want to subtract from the parent height.
  • offsets: An array of numbers that specify any additional height offsets that you want to subtract from the parent height.

πŸŽ‰ The hook returns an array with two elements:

  • restHeight: The remaining height of the container after subtracting the child elements and offsets.
  • action: An object with a single function recalculateHeight that you can call to recalculate the container height when needed.

πŸ’‘ Overall, useRestHeight simplifies the process of dynamically adjusting the layout of container elements in your React applications. Want to see a demo? Check it out!

useIntersectionObserver: Track element visibility changes.

This hook allows you to detect when an element becomes visible in the viewport. You can use it to implement lazy-loading, infinite scrolling, or any other functionality that requires you to track an element's visibility.

To use it, you simply need to pass a RefObject to the element you want to observe, along with any optional configuration options like the root element, root margin, and threshold. The hook returns a tuple containing the IntersectionObserverEntry for the observed element, and an empty object that you can use to dispatch any actions.

So, if you want to make your web app more performant and user-friendly, give useIntersectionObserver a try! πŸ‘Demo is here

useOutClick: Handle Outside Clicks In React!

The code exports a single custom hook, useOutClick, which takes a handler function as a parameter and returns a tuple containing a ref object and an empty action object. Here's how to use it:

  • Import: Import the useOutClick hook from its source file using the following code:
import { useOutClick } from 'microhook';
  • Usage: Use the useOutClick hook in your functional component as follows:
const MyComponent = () => {
  const handleClickOutside = () => {
    // do something when user clicks outside of the element
  };

  const ref = useOutClick<HTMLDivElement>(handleClickOutside);

  return (
    <div ref={ref}>
      {/* content of the element to monitor */}
    </div>
  );
};

In this example, we define a handleClickOutside function that will be called when the user clicks outside of the element. We then call the useOutClick hook, passing in the handleClickOutside function. The useOutClick hook returns a tuple containing a ref that we attach to the element we want to monitor, in this case a div, and an empty action object.

  • Types: The useOutClick hook is a generic function that takes a type parameter T that extends HTMLElement. This allows TypeScript to ensure that the ref object returned by the hook is properly typed to the monitored element.

That's it! Now you can detect when the user clicks outside of a specified element and take appropriate action.Demo is here

DOM

usePortal: Teleport Your React Components Anywhere!

πŸš€ usePortal is a React hook that allows you to easily render content outside of the component hierarchy. Simply pass in a render function and a container, and usePortal will take care of the rest. It's perfect for creating modals, tooltips, and other UI elements that need to be rendered outside of the main content area.

Here's an example of how to use it:

import { usePortal } from 'microhook';

function MyModal() {
  const { render } = usePortal(() => (
    <div className="modal">
      <h2>Modal title</h2>
      <p>Modal content goes here...</p>
    </div>
  ), document.body);

  return render();
}

πŸ‘‰ Make sure to wrap the render function in useCallback and memoize your component with React.memo for optimal performance. For more information!

useMeasure: Track Element Measurements With Ease!

To use the useMeasure hook, first import it into your component with the following code:

import { useMeasure } from 'microhook';

Then, declare a ref for the element you want to measure with the useRef hook:

const ref = useRef(null);

Finally, call the useMeasure hook with the ref as an argument, and destructure the measure object from the returned value:

const [measure] = useMeasure(ref);

You can now access the measurements of the element in your component with measure.width, measure.height, measure.top, measure.right,measure.bottom, measure.left, measure.x, and measure.y. Whenever the size or position of the element changes, the measure object will automatically update with the new values. For more information!