react-use-light
v1.2.8
Published
React use without external dependencies.
Downloads
22
Readme
react-use-light
react-use without external dependencies. Collection of essential React Hooks.
Fork from streamich/react-use
Install
npm i react-use-light
or
yarn add react-use-light
Extra 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 Component[
useDebounceFunction
] - Debouce Function for React[
pick
,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. ![][img-demo]useGeolocation
— tracks geo location state of user's device. ![][img-demo]useHover
anduseHoverDirty
— tracks mouse hover state of some element. ![][img-demo]useHash
— tracks location hash value. ![][img-demo]useIdle
— tracks whether user is being inactive.useKey
,useKeyPress
, anduseKeyPressEvent
— track keys. ![][img-demo][
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';
useLocation
anduseSearchParam
— tracks page navigation bar location state.useLongPress
— tracks long press gesture of some element.useMedia
— tracks state of a CSS media query. ![][img-demo]useMediaDevices
— tracks state of connected hardware devices.useMotion
— tracks state of device's motion sensor.useMouse
anduseMouseHovered
— tracks state of mouse position. ![][img-demo]useMouseWheel
— tracks deltaY of scrolled mouse wheel. ![][img-demo]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. ![][img-demo]useScrolling
— tracks whether HTML element is scrolling.useStartTyping
— detects when user starts typing.useWindowScroll
— tracksWindow
scroll position. ![][img-demo]useWindowSize
— tracksWindow
dimensions. ![][img-demo]useMeasure
anduseSize
— tracks an HTML element's dimensions. ![][img-demo]
useAudio
— plays audio and exposes its controls. ![][img-demo]useClickAway
— triggers callback when user clicks outside target area.useCss
— dynamically adjusts CSS.useDrop
anduseDropArea
— tracks file, link and copy-paste drops.useSlider
— provides slide behavior over any HTML element. ![][img-demo]useSpeech
— synthesizes speech from a text string. ![][img-demo]useVibrate
— provide physical feedback using the Vibration API. ![][img-demo]useVideo
— plays video, tracks its state, and exposes playback controls. ![][img-demo]
useRaf
— re-renders component on eachrequestAnimationFrame
.useInterval
anduseHarmonicIntervalFn
— re-renders component on a set interval usingsetInterval
.useTimeout
— re-renders component after a timeout.useTimeoutFn
— calls given function after a timeout. ![][img-demo]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 anasync
function.useCopyToClipboard
— copies text to clipboard.useDebounce
— debounces a function. ![][img-demo]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
.useThrottle
anduseThrottleFn
— throttles a function. ![][img-demo]useTitle
— sets title of the page.usePermission
— query permission status for browser APIs.
useEffectOnce
— a modifieduseEffect
hook that only runs once.useEvent
— subscribe to events.useLifecycles
— callsmount
andunmount
callbacks.useMountedState
anduseUnmountPromise
— track if component is mounted.usePromise
— resolves promise only while component is mounted.useLogger
— logs in console as component goes through life-cycles.useMount
— callsmount
callbacks.useUnmount
— callsunmount
callbacks.useUpdateEffect
— run aneffect
only on updates.useIsomorphicLayoutEffect
—useLayoutEffect
that does not show warning when server-side rendering.
createMemo
— factory of memoized hooks.createReducer
— factory of reducer hooks with custom middleware.createReducerContext
andcreateStateContext
— factory of hooks for a sharing state between components.useDefault
— returns the default value when state isnull
orundefined
.useGetSet
— returns state getterget()
instead of raw state.useLatest
— returns the latest state or propsusePrevious
— returns the previous state or props. ![][img-demo]usePreviousDistinct
— likeusePrevious
but with a predicate to determine ifprevious
should update.useObservable
— tracks latest value of anObservable
.useRafState
— createssetState
method which only updates afterrequestAnimationFrame
. ![][img-demo]useSetState
— createssetState
method which works likethis.setState
. ![][img-demo]useStateList
— circularly iterates over an array. ![][img-demo]useToggle
anduseBoolean
— tracks state of a boolean. ![][img-demo]useCounter
— tracks state of a number. ![][img-demo]useList
~anduseUpsert
~ — tracks state of an array. ![][img-demo]useMap
— tracks state of an object. ![][img-demo]useSet
— tracks state of a Set. ![][img-demo]useQueue
— implements simple queue.useStateWithHistory
— stores previous state values and provides handles to travel through them. ![][img-demo]useMediatedState
— like the regularuseState
but with mediation by custom function. ![][img-demo]useFirstMountState
— check if current render is first. ![][img-demo]useRendersCount
— count component renders. ![][img-demo]createGlobalState
— cross component shared state.![][img-demo]useMethods
— neat alternative touseReducer
. ![][img-demo]