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

@aboutbits/react-toolbox

v0.2.5

Published

Tools for React

Downloads

358

Readme

React Toolbox

npm package license

This package includes different tools that support you with common tasks.

Table of content

Usage

First, you have to install the package:

npm install @aboutbits/react-toolbox

Second, you can make use of the different tools.

useInterval

The useInterval hook calls a function at specified intervals. The code of this hook is taken from Dan Abramov's blog post.

The hook takes two parameters:

  • callback: The callback function that should be executed.
  • delay: The delay in milliseconds or null, if the interval should be paused.
import React, { useState } from 'react'
import { useInterval } from '@aboutbits/react-toolbox'

const MyCommponent = () => {
  const [step, setStep] = useState(10)

  useInterval(
    () => {
      setStep(step - 1)
    },
    step === 0 ? null : 1000
  )

  return <p>Countdown: {step}</p>
}

Async Data

This part includes a utility component, that can be used to render loading, success and error views based on async state.

import React, { useEffect } from 'react'
import { AsyncView } from '@aboutbits/react-toolbox'

type Data = {
  greeting: string
}

type Error = {
  message: string
}

const MyCommponent = () => {
  const [data, setData] = useState<Data | undefined>()
  const [error, setError] = useState<Error | undefined>()

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then((response) => setData(response.json()))
      .catch((error) => setError(error))
  })

  return (
    <AsyncView
      data={data}
      error={error}
      renderLoading={<div>Loading</div>}
      renderSuccess={(data) => <div>{data.greeting}</div>}
      renderError={(error) => <div>{error.message}</div>}
    />
  )
}

And using SWR:

import React, { useEffect } from 'react'
import { useSWR } from 'swr'
import { AsyncView } from '@aboutbits/react-toolbox'

type Data = {
  greeting: string
}

type Error = {
  message: string
}

const MyCommponent = () => {
  const { data, error } = useSWR('https://jsonplaceholder.typicode.com/todos/1')

  return (
    <AsyncView
      data={data}
      error={error}
      renderLoading={'Loading'}
      renderSuccess={'Success'}
      renderError={'Error'}
    />
  )
}

LocationProvider

This part includes a React context that fetches the geolocation at a given interval.

import { LocationProvider } from '@aboutbits/react-toolbox'

const MyApp = () => {
  return (
    <LocationProvider highAccuracy={true} delay={20000}>
      {children}
    </LocationProvider>
  )
}

The context provider takes two props:

  • highAccuracy: defines if the location should be fetched with high accuracy. Read more on the Geolocation API doc.
  • delay: the delay in milliseconds between each fetch
import { useContext } from 'react'
import { LocationContext } from '@aboutbits/react-toolbox'

const MyComponent = () => {
  const { location } = useContext(LocationContext)

  return location ? (
    <div>
      Your location is: {location.coords.latitude}, {location.coords.longitude}
    </div>
  ) : (
    <div>Unable to get your location</div>
  )
}

useMatchMediaQuery

This hook is based on the window.matchQuery API and can be used to find out if a certain media query matches the current window.

import { useMatchMediaQuery } from '@aboutbits/react-toolbox'

const TestComponent = () => {
  const matches = useMatchMediaQuery('(min-width : 500px)')
  if (matches) return <div>visible</div>
  return null
}

useDebounce

Use this hook to prevent the component from re-rendering too many times. Useful to avoid making unnecessary API calls.

export default function TestComponent() {
  const [value, setValue] = useState('')
  const debouncedValue = useDebounce(value, 500)

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    setValue(event.target.value)
  }

  // Fetch API (optional)
  useEffect(() => {
    // Do fetch here...
    // Triggers when "debouncedValue" changes
  }, [debouncedValue])

  return (
    <div>
      <p>Value real-time: {value}</p>
      <p>Debounced value: {debouncedValue}</p>
      <input type="text" value={value} onChange={handleChange} />
    </div>
  )
}

useIsMounted

In React, a component is deleted from memory once unmounted. Changing the state in an unmounted component will result in an error. This is preferrably solved passing a cleanup function to useEffect. However, there are some cases like Promise or API calls where it's impossible to know if the component is still mounted at the resolve time. This hook returns a function that can be used to verify at the resolve time whether the component is still mounted.

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function Child() {
  const [data, setData] = useState('loading')
  const isMounted = useIsMounted()

  // simulate an api call and update state
  useEffect(() => {
    void delay(3000).then(() => {
      if (isMounted()) {
        setData('OK')
      }
    })
  }, [isMounted])

  return <p>{data}</p>
}

export default function TestComponent() {
  const [isVisible, setVisible] = useState<boolean>(false)

  const toggleVisibility = () => setVisible((state) => !state)

  return (
    <>
      <button onClick={toggleVisibility}>{isVisible ? 'Hide' : 'Show'}</button>

      {isVisible && <Child />}
    </>
  )
}

Build & Publish

To publish the package commit all changes and push them to main. Then run one of the following commands locally:

npm version patch
npm version minor
npm version major

Information

About Bits is a company based in South Tyrol, Italy. You can find more information about us on our website.

Support

For support, please contact [email protected].

Credits

License

The MIT License (MIT). Please see the license file for more information.