react-use-light v1.2.8
react-use-light
react-use without external dependencies. Collection of essential React Hooks.
Fork from streamich/react-use
Install
npm i react-use-lightor
yarn add react-use-lightExtra Hooks
useAudioControls
Just like useAudio returns the audio element,a ref to the element and the controls. this also returns the time played "00:01" and the timeleft "02:10" in minutes.
import { useAudioControls } from 'react-use-light';
export function App(track) {
const [{ audio, controls, state, currentAudioTimeRef, currentAudioTimeLeftRef, ref }] = useAudioControls({
src: track.audioUrl,
autoPlay: false,
loop: false,
'aria-label': track.name,
});
return (
<div>
<h1>{track.name}</h1>
{audio}
</div>
);
}useDate
import React from 'react';
import { useDate, formatDate } from 'react-use-light';
export function Test() {
const [date] = useDate();
return <h1>{formatDate(date)}</h1>;
}createContextHook
import { createContext } from 'react';
import { createContextHook } from 'react-use-light';
import { API_URL } from '../constants';
import { AppContextState } from './reducer';
const initialState: AppContextState = {
auth: {
user: undefined,
errorMessage: undefined,
loading: false,
},
surveys: {
openSurveys: [],
},
};
export const AppContext = createContext(initialState);
let fetched = false;
export const useAppContext = createContextHook(AppContext, (context) => {
async function fetchSurveys() {
if (!fetched) {
const res = await fetch(API_URL + '/surveys');
const data = await res.json();
fetched = true;
return data.surveys;
} else {
console.log('returning from cache');
return context.surveys.openSurveys;
}
}
return { ...context, fetchSurveys };
});CreateContextReducer
const [ContextProvider, useContext, Context] = createContextReducer<AppState, Actions>();import { createContextReducer, Action } from 'react-use-light';
import { useState } from 'react';
// CREATE STATE TYPE
interface AppState {
notes: string[];
user: User | undefined;
}
//CREATE ACTIONS TYPE (Should extend Action interface >> {type:string, payload?:any})
type Actions = SetUserAction | SetNotesAction;
interface SetUserAction extends Action {
type: 'SET_USER';
payload: User | undefined;
}
interface SetNotesAction extends Action {
type: 'SET_NOTES';
payload: string[];
}
interface User {
name: string;
email: string;
}
//Pass the State Type and Actions Type to the create function in order to get a properly typed context.
// @returns >>> [ContextProvider, ContextHook, and Context]
const [AppContextProvider, useAppContext, AppContext] = createContextReducer<AppState, Actions>();
//create state reducer for the defined types
const reducer = (state: AppState, action: Actions): AppState => {
switch (action.type) {
case 'SET_NOTES':
return { ...state, notes: action.payload };
case 'SET_USER':
return { ...state, user: action.payload };
default:
return { ...state };
}
};
// initial state
const initialState: AppState = {
notes: [],
user: undefined,
};
// USE ContextProvider by passing initial state and the reducer function.
export function App() {
return (
<AppContextProvider initialState={initialState} reducer={reducer}>
<PageOne />
</AppContextProvider>
);
}
// Use in ContextProvider Children
function PageOne() {
const [{ notes }, dispatch] = useAppContext();
const [note, setNote] = useState('');
function addNote() {
if (note && note.trim() !== '') {
dispatch({
type: 'SET_NOTES',
payload: [...notes, note],
});
setNote('');
}
}
return (
<div>
<h1>Inside Context</h1>
<form
onSubmit={(e) => {
e.preventDefault();
addNote();
}}
>
<div>
<input placeholder="add note" value={note} onChange={(e) => setNote(e.target.value)} />
</div>
</form>
<div>
{notes.map((n) => (
<p key={n}>{n}</p>
))}
</div>
</div>
);
}Others
combineReducers- combines React.Reducer objects into 1.RoutePathGetter- Class to orginize the router paths of an application.SkeletonElement- React Skeleton Component.createGlobalStyle- Creates global styles (appends to head). you can pass a string or an object with CSSProperties. eg. {body: {backgroundColor: 'red'}}removeGlobalStyle- Removes global styles by id. (id returned by createGlobalStyle)ErrorBoundary- Error Boundary ComponentuseDebounceFunction- Debouce Function for Reactpick,debounceFunction,throttleFunction,rgbToHex,degreesToRadians,hexToRGB,interpolateColor,radiansToDegrees,removeFirst- Utility functions.useRefModel- creates form elements 2 way binding on the value.useThemeStyles- toggles between theme styles. 'dark'|'light'. see exampleconst [theme, setTheme, toggleTheme] = useThemeStyles( 'light', // default theme `:root{--app-color: black;}` // dark styles, `:root{--app-color: white;}` // light styles );
React-Use Library Documentation
useBattery— tracks device battery state.useGeolocation— tracks geo location state of user's device.useHoveranduseHoverDirty— tracks mouse hover state of some element.useHash— tracks location hash value.useIdle— tracks whether user is being inactive.useKey,useKeyPress, anduseKeyPressEvent— track keys.useKeyboardJs— detects complex key combos like detecting when multiple keys are held down at the same. Needs to be imported directly because of dependency onkeyboardjs.import useKeyboardJs from 'react-use-light/esm/useKeyboardJs';useLocationanduseSearchParam— tracks page navigation bar location state.useLongPress— tracks long press gesture of some element.useMedia— tracks state of a CSS media query.useMediaDevices— tracks state of connected hardware devices.useMotion— tracks state of device's motion sensor.useMouseanduseMouseHovered— tracks state of mouse position.useMouseWheel— tracks deltaY of scrolled mouse wheel.useNetwork— tracks state of user's internet connection.useOrientation— tracks state of device's screen orientation.usePageLeave— triggers when mouse leaves page boundaries.useScratch— tracks mouse click-and-scrub state.useScroll— tracks an HTML element's scroll position.useScrolling— tracks whether HTML element is scrolling.useStartTyping— detects when user starts typing.useWindowScroll— tracksWindowscroll position.useWindowSize— tracksWindowdimensions.useMeasureanduseSize— tracks an HTML element's dimensions.
useAudio— plays audio and exposes its controls.useClickAway— triggers callback when user clicks outside target area.useCss— dynamically adjusts CSS.useDropanduseDropArea— tracks file, link and copy-paste drops.useSlider— provides slide behavior over any HTML element.useSpeech— synthesizes speech from a text string.useVibrate— provide physical feedback using the Vibration API.useVideo— plays video, tracks its state, and exposes playback controls.
useRaf— re-renders component on eachrequestAnimationFrame.useIntervalanduseHarmonicIntervalFn— re-renders component on a set interval usingsetInterval.useTimeout— re-renders component after a timeout.useTimeoutFn— calls given function after a timeout.useUpdate— returns a callback, which re-renders component when called.useSpring— interpolates number over time according to spring dynamics. Needs to be imported directly because of dependency onrebound.import useSpring from 'react-use-light/esm/useSpring';
useAsync,useAsyncFn, anduseAsyncRetry— resolves anasyncfunction.useCopyToClipboard— copies text to clipboard.useDebounce— debounces a function.useLocalStorage— manages a value inlocalStorage.useLockBodyScroll— lock scrolling of the body element.useRafLoop— calls given function inside the RAF loop.useSessionStorage— manages a value insessionStorage.useThrottleanduseThrottleFn— throttles a function.useTitle— sets title of the page.usePermission— query permission status for browser APIs.
useEffectOnce— a modifieduseEffecthook that only runs once.useEvent— subscribe to events.useLifecycles— callsmountandunmountcallbacks.useMountedStateanduseUnmountPromise— track if component is mounted.usePromise— resolves promise only while component is mounted.useLogger— logs in console as component goes through life-cycles.useMount— callsmountcallbacks.useUnmount— callsunmountcallbacks.useUpdateEffect— run aneffectonly on updates.useIsomorphicLayoutEffect—useLayoutEffectthat does not show warning when server-side rendering.
createMemo— factory of memoized hooks.createReducer— factory of reducer hooks with custom middleware.createReducerContextandcreateStateContext— factory of hooks for a sharing state between components.useDefault— returns the default value when state isnullorundefined.useGetSet— returns state getterget()instead of raw state.useLatest— returns the latest state or propsusePrevious— returns the previous state or props.usePreviousDistinct— likeusePreviousbut with a predicate to determine ifpreviousshould update.useObservable— tracks latest value of anObservable.useRafState— createssetStatemethod which only updates afterrequestAnimationFrame.useSetState— createssetStatemethod which works likethis.setState.useStateList— circularly iterates over an array.useToggleanduseBoolean— tracks state of a boolean.useCounter— tracks state of a number.useList~anduseUpsert~ — tracks state of an array.useMap— tracks state of an object.useSet— tracks state of a Set.useQueue— implements simple queue.useStateWithHistory— stores previous state values and provides handles to travel through them.useMediatedState— like the regularuseStatebut with mediation by custom function.useFirstMountState— check if current render is first.useRendersCount— count component renders.createGlobalState— cross component shared state.useMethods— neat alternative touseReducer.