Utility library for common React hooks such as useMountEffect, useUpdateEffect, useUnmount effect etc..
npm install @kmpizmad/react-hooks-util- Introduction
- Guidelines
- Lifecycle hooks
- useMountEffect
- useUnmountEffect
- useUpdateEffect
- usePrevState
- DOM hooks
- useToggle
- useEventListener
- useScript
- Util hooks
- useTimeout
- useDebounce
- useTextShortener
- useOnlineStatus
- useRenderCount
- useDebugInfo
- useLocalStorage
- useSessionStorage
- Asynchronous hooks
- useAsync
- useFetch
- Types
- AsyncObject
- AsyncError
- DebugInfo
- FetchConfig
- State
- StorageObject
- TimeoutObject
- ToggleObject
- Value
> Utility library for common React hooks
The idea was to create a library that contains common functionalities abstracted into hooks rather than implementing them everytime in every project.
- Checkout the latest updates in the [changelog][changelog_url]
- See our [contributing guidelines][contributing_url]
- See our [Support Guide][support_url]
- See our [Security Policy][security_url]
_type_: (effect: React.EffectCallback) => void
Represents the componentDidMount method from React class components
``typescript
const DidMountComponent = () => {
const [value, setValue] = React.useState
const [dependency, setDependency] = React.useState
useMountEffect(() => {
setValue(dependency + 1);
});
return (
$3
_type_:
(effect: React.EffectCallback, deps: React.DependencyList = []) => voidRepresents the
componentWillUnmount method from React class components`typescript
const WillUnmountComponent = () => {
const [value, setValue] = React.useState(0); useUnmountEffect(() => {
setValue(-1);
});
return
{value};
};
`$3
_type_:
(effect: React.EffectCallback, deps?: React.DependencyList) => voidRenders whenever a dependency changes or if provided without a dependency list, renders on any change. Avoid providing an empty dependency list
`typescript
const DidUpdateComponent = () => {
const [value, setValue] = React.useState(0);
const [dependency, setDependency] = React.useState(0); useUpdateEffect(() => {
setValue(dependency);
}, [dependency]);
return (
{value}
);
};
`$3
_type_:
(state: PrevState) => PrevStategetSnapshotBeforeUpdate, componentShouldUpdate and componentWillRecieveProps combined in one. Captures the previous state based on the input object`typescript
const PrevStateComponent = () => {
const [dependency, setDependency] = React.useState(0);
const prevState = usePrevState({ dependency }); return (
{prevState?.dependency || '-1'}
);
};
`DOM hooks
$3
_type_:
(initialValue?: boolean) => ToggleObjectToggles state between
true and false`typescript
const ToggleComponent = (props: { initialValue?: boolean }) => {
const { value, toggle } = useToggle(props.initialValue);
return (
{value.toString()}
);
};
`$3
_type_:
(type: keyof WindowEventMap, callback: (event: Event) => void, element: HTMLElement | Document | (Window & typeof globalThis) = window) => voidAttaches a global event listener to the
element (window object by default).`typescript
const EventListenerComponent = () => {
const [value, setValue] = React.useState('Loading'); useEventListener('load', () => {
setTimeout(() => {
setValue('Hello World!');
}, 100);
});
return
{value};
};
`$3
_type_:
(url: string) => AsyncObjectWithoutDataLoads in a script and adds a new
script node to the DOM.`typescript
const ScriptComponent = () => {
const { loading, error } = useScript(
'https://code.jquery.com/jquery-3.6.0.min.js'
); if (loading) return
Loading;
if (error) return Error; return (
{Object.keys(window)
.includes('$')
.toString()}
);
};
`Util hooks
$3
_type_:
(callback: () => void, ms: number) => TimeoutObjectBasically
setTimeout as a hook.`typescript
const TimeoutComponent = () => {
const [count, setCount] = React.useState(10);
const { clear, reset } = useTimeout(() => setCount(0), 1000); return (
{count}
);
};
`$3
_type_:
(callback: () => void, ms: number, deps: React.DependencyList = []) => void`typescript
const DebounceComponent = () => {
const [count, setCount] = React.useState(0);
const [dependency, setDependency] = React.useState(10);
useDebounce(() => setCount(dependency), 200, [dependency]); return (
{count}
);
};
`$3
_type_:
(text: string, options: TextShortenerOptions) => stringShortens a text to a specified
limit. Customizable through options.`typescript
const TextShortenerComponent = (props: Omit) => {
const [limit, setLimit] = React.useState(11);
const short = useTextShortener('Lorem ipsum dolor sit amet', {
limit,
...props,
}); return (
{short}
);
};
`$3
_type_:
() => booleanReturns
true or false. Depends on the browser agent status.$3
_type_:
() => number$3
_type_:
`typescript
const DebugComponent: React.FC<{ count: number }> = props => {
const [count, setCount] = React.useState(props.count);
const debug = useDebugInfo(DebugComponent, { count }); return (
{JSON.stringify(debug)}
);
};
`$3
_type_:
(key: string, defaultValue: Value) => StorageObjectHandles and stores data in
window.localStorage`typescript
const LocalStorageComponent = () => {
const { value, update, remove } = useLocalStorage('test', 'Hello World!');
return (
{value}
);
};
`$3
_type_:
(key: string, defaultValue: Value) => StorageObjectHandles and stores data in
window.sessionStorage`typescript
const SessionStorageComponent = () => {
const { value, update, remove } = useSessionStorage('test', 'Hello World!');
return (
{value}
);
};
`Asynchronous hooks
$3
_type_:
Handles async functions, re-evaluates whenever a dependency changes
`typescript
const AsyncComponent = (props: { success?: boolean }) => {
const { loading, error, data } = useAsync(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
props.success ? resolve('Hello World!') : reject({ message: 'Error' });
}, 1000);
});
}); return (
{loading.toString()}
{error && {JSON.stringify(error)}}
{data && {data}}
);
};
`$3
_type_:
Handles API requests, uses the built-in
fetch moduleTypes
$3
`typescript
{
loading: boolean;
error: AsyncError | undefined;
data: T | undefined;
}
`$3
`typescript
{
message: string;
[key: number | string]: any;
}
`$3
`typescript
{
renderCount: number;
changedProps: Record;
timeSinceLastRender: number;
lastRenderTimestamp: number;
}
`$3
`typescript
{
url: string;
options?: RequestInit
};
`$3
`typescript
{
[key: number | string]: any
};
`$3
`typescript
{
value: Value;
update: (value: Value) => void;
remove: () => void;
}
`$3
`typescript
{
reset: () => void;
clear: () => void;
}
`$3
`typescript
{
value: boolean;
toggle: () => void
}
`$3
`typescript
string | number | boolean | Record | null | undefined
``[changelog_url]: https://github.com/kmpizmad/react-hooks-util/blob/master/docs/CHANGELOG.md
[contributing_url]: https://github.com/kmpizmad/react-hooks-util/tree/master/docs/CONTRIBUTING.md
[support_url]: https://github.com/kmpizmad/react-hooks-util/tree/master/docs/SUPPORT.md
[security_url]: https://github.com/kmpizmad/react-hooks-util/tree/master/docs/SECURITY.md