This package includes different tools that support you with common tasks.
First, you have to install the package:
npm install @aboutbits/react-toolboxSecond, you can make use of the different tools.
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.
importReact,{useState}from'react'import{useInterval}from'@aboutbits/react-toolbox'constMyCommponent=()=>{const[step,setStep]=useState(10)useInterval(()=>{setStep(step-1)},step===0 ? null : 1000)return<p>Countdown: {step}</p>}This part includes a utility component, that can be used to render loading, success and error views based on async state.
importReact,{useEffect}from'react'import{AsyncView}from'@aboutbits/react-toolbox'typeData={greeting: string}typeError={message: string}constMyCommponent=()=>{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(<AsyncViewdata={data}error={error}renderLoading={<div>Loading</div>}renderSuccess={(data)=><div>{data.greeting}</div>}renderError={(error)=><div>{error.message}</div>}/>)}And using SWR:
importReact,{useEffect}from'react'import{useSWR}from'swr'import{AsyncView}from'@aboutbits/react-toolbox'typeData={greeting: string}typeError={message: string}constMyCommponent=()=>{const{ data, error }=useSWR('https://jsonplaceholder.typicode.com/todos/1')return(<AsyncViewdata={data}error={error}renderLoading={'Loading'}renderSuccess={'Success'}renderError={'Error'}/>)}This part includes a React context that fetches the geolocation at a given interval.
import{LocationProvider}from'@aboutbits/react-toolbox'constMyApp=()=>{return(<LocationProviderhighAccuracy={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'constMyComponent=()=>{const{ location }=useContext(LocationContext)returnlocation ? (<div>
Your location is: {location.coords.latitude}, {location.coords.longitude}</div>) : (<div>Unable to get your location</div>)}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'constTestComponent=()=>{constmatches=useMatchMediaQuery('(min-width : 500px)')if(matches)return<div>visible</div>returnnull}Use this hook to prevent the component from re-rendering too many times. Useful to avoid making unnecessary API calls.
exportdefaultfunctionTestComponent(){const[value,setValue]=useState('')constdebouncedValue=useDebounce(value,500)consthandleChange=(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><inputtype="text"value={value}onChange={handleChange}/></div>)}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.
constdelay=(ms: number)=>newPromise((resolve)=>setTimeout(resolve,ms))functionChild(){const[data,setData]=useState('loading')constisMounted=useIsMounted()// simulate an api call and update stateuseEffect(()=>{voiddelay(3000).then(()=>{if(isMounted()){setData('OK')}})},[isMounted])return<p>{data}</p>}exportdefaultfunctionTestComponent(){const[isVisible,setVisible]=useState<boolean>(false)consttoggleVisibility=()=>setVisible((state)=>!state)return(<><buttononClick={toggleVisibility}>{isVisible ? 'Hide' : 'Show'}</button>{isVisible&&<Child/>}</>)}To build and publish the package, visit the GitHub Actions page of the repository.
You can choose between two workflows:
Release Packageto publish a new version of the package.Pre-Release Packageto publish a new pre-release version of the package.
Note: Pre-releases need to be supplied with a pre-id.
Note: To increment a pre-release, you have to run the normal release workflow and select "prerelease". For this action you need to already be on a pre-release version.
About Bits is a company based in South Tyrol, Italy. You can find more information about us on our website.
For support, please contact info@aboutbits.it.
The MIT License (MIT). Please see the license file for more information.