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-any-hook

v1.3.4

Published

All react.js custom hooks you frequently use.

Downloads

25

Readme

useAnyHook();

npm version npm downloads

A collection of commonly used custom React.js hooks for various use cases in front-end development.

Installation

You can install the package using npm:

npm install use-any-hook

Content Summary

Thi is a quide through the usage process, jump directly to the hook you want:

useFetch
useDebounce
useClickOutside
useLocalStorageWithExpiry
useForm
useDarkMode
useInfiniteScroll
useMousePosition
useGeoLocation

Usage

A quick quide for each hook in the use-any-hook package

// Import your desired custom hook 1st.
import { useInfiniteScroll } from "use-any-hook";

1. useFetch

useFetch is a hook for making HTTP requests and managing the loading and error state of the fetched data.

function MyComponent() {
  const [data, loading, error] = useFetch("https://api.example.com/data");

  useEffect(() => {
    // Handle data when it is available
    if (data) {
      // Do something with the fetched data
    }
  }, [data]);

  return (
    <div>
      {loading ? "Loading..." : null}
      {error ? "Error: Unable to fetch data" : null}
      {data ? <div>Data: {data}</div> : null}
    </div>
  );
}

2. useDebounce

useDebounce is a hook that allows you to debounce a value or function to delay its execution until a certain timeout has passed.

function MyComponent() {
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 300);

  return (
    <input
      type="text"
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}

3. useClickOutside

useClickOutside detects clicks outside of a specified element and triggers a callback.

function MyComponent() {
  const ref = useRef();
  const [isOpen, setIsOpen] = useState(false);

  useClickOutside(ref, () => {
    setIsOpen(false);
  });

  return (
    <div ref={ref}>{isOpen ? "Click outside to close" : "Click to open"}</div>
  );
}

4. useLocalStorageWithExpiry

useLocalStorageWithExpiry extends useLocalStorage to store values with an expiration time.

function MyComponent() {
  const [data, setData] = useLocalStorageWithExpiry("myData", null, 60000);

  return <div>Data from local storage: {data}</div>;
}

5. useForm

useForm is a hook for handling form input state and simplifying form management.

function MyComponent() {
  const { values, handleChange, resetForm } = useForm({
    username: "",
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    // Use the form values for submission
    console.log("Submitted data:", values);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="username"
        value={values.username}
        onChange={handleChange}
        placeholder="Username"
      />

      <button type="submit">Submit</button>
      <button type="button" onClick={resetForm}>
        Reset
      </button>
    </form>
  );
}

6. useDarkMode

useDarkMode is a hook for managing the theme, such as toggling between light and dark mode.

function MyComponent() {
  const { isDarkMode, toggleTheme } = useDarkMode();

  return (
    <div className={isDarkMode ? "dark-mode" : "light-mode"}>
      <button onClick={toggleTheme}>Toggle Theme</button>
      {isDarkMode ? "Dark Mode" : "Light Mode"}
    </div>
  );
}

7. useInfiniteScroll

useInfiniteScroll This hook helps you implement infinite scrolling in your application, fetching and appending data as the user scrolls.

function InfiniteScrollExample() {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);

  // Simulated function to fetch more data
  const fetchMoreData = async () => {
    // Simulated API call to fetch more items (e.g., from a backend server)
    const response = await fetch(`https://api.example.com/items?page=${page}`);
    const newData = await response.json();

    // Update the items and page
    setItems([...items, ...newData]);
    setPage(page + 1);
  };

  const isFetching = useInfiniteScroll(fetchMoreData);

  useEffect(() => {
    // Initial data fetch when the component mounts
    fetchMoreData();
  }, []);

  return (
    <div>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      {isFetching && <p>Loading more items...</p>}
    </div>
  );
}

8. useMousePosition

useMousePosition is a hook for detecting the mouse position in a specific div x,y axis.

function MyComponent() {
  const ref = React.useRef(null);
  const { x, y } = useMousePosition(ref);

  return (
    <div ref={ref}>
      Mouse Position: `x-axis: ${x}, y-axis: ${x}`
    </div>
  );
}

9. useGeoLocation

useGeoLocation is a hook for detecting the user accurate position in latitude and longitude after asking for permission.

function MyComponent() {
  const { location, error } = useGeoLocation();

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {location ? (
        <div>
          Latitude: {location.latitude}, Longitude: {location.longitude}
        </div>
      ) : (
        <div>Fetching location...</div>
      )}
    </div>
  );
}