diff --git a/.eslintrc b/.eslintrc
deleted file mode 100644
index 0475b64f..00000000
--- a/.eslintrc
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "extends": [
- "airbnb-base",
- "airbnb-typescript"
- ],
- "parser": "@typescript-eslint/parser",
- "parserOptions": {
- "ecmaVersion": 6,
- "project": "./tsconfig.esm.json"
- },
- "plugins": [
- "chai-expect",
- "react-hooks"
- ],
- "env": {
- "browser": true,
- "mocha": true
- },
- "rules": {
- "max-len": ["error", {"code": 140}],
- "semi": [2, "never"],
- "@typescript-eslint/semi": "off",
- "linebreak-style": "off",
- "object-curly-newline": "off",
- "react/jsx-filename-extension": "off"
- },
- "overrides": [
- {
- "files": [
- "*.test.js",
- "*.spec.js",
- "*.test.jsx",
- "*.spec.jsx"
- ],
- "globals": {
- "expect": "readonly",
- "should": "readonly",
- "sinon": "readonly"
- },
- "rules": {
- "no-unused-expressions": "off"
- }
- }
- ]
-}
diff --git a/.eslintrc.js b/.eslintrc.js
new file mode 100644
index 00000000..8918fd5e
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,57 @@
+module.exports = {
+ env: {
+ browser: true,
+ es2021: true
+ },
+ extends: [
+ 'plugin:react/recommended',
+ 'standard-with-typescript'
+ ],
+ parserOptions: {
+ project: './tsconfig.json',
+ ecmaVersion: 'latest',
+ sourceType: 'module'
+ },
+ plugins: [
+ 'react'
+ ],
+ rules: {
+ 'max-len': [
+ 'error',
+ {
+ code: 140
+ }
+ ],
+ semi: [
+ 2,
+ 'never'
+ ],
+ '@typescript-eslint/semi': 'off',
+ 'linebreak-style': 'off',
+ 'object-curly-newline': 'off',
+ 'react/jsx-filename-extension': 'off',
+ 'import/no-named-as-default': 'off',
+ 'import/no-named-as-default-member': 'off',
+ '@typescript-eslint/explicit-function-return-type': 'off',
+ '@typescript-eslint/strict-boolean-expressions': 'off',
+ '@typescript-eslint/no-non-null-assertion': 'off'
+ },
+ overrides: [
+ {
+ files: [
+ '*.test.js',
+ '*.spec.js',
+ '*.test.jsx',
+ '*.spec.jsx'
+ ],
+ globals: {
+ expect: 'readonly',
+ should: 'readonly',
+ sinon: 'readonly'
+ },
+ rules: {
+ 'no-unused-expressions': 'off'
+ }
+ }
+ ]
+}
diff --git a/.github/workflows/branch-tests.yml b/.github/workflows/branch-tests.yml
index 25219cb9..55c641dd 100644
--- a/.github/workflows/branch-tests.yml
+++ b/.github/workflows/branch-tests.yml
@@ -11,11 +11,11 @@ on:
jobs:
test:
if: "!contains(github.event.head_commit.message, 'skip ci')"
- runs-on: ${{ matrix.os }}
+ runs-on: ubuntu-latest
strategy:
matrix:
- node-version: 18
+ node-version: [ 18.14 ]
steps:
- uses: actions/checkout@v2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index eff9e606..b973f151 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -17,11 +17,11 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
- node-version: 18
+ node-version: 18.14
registry-url: https://registry.npmjs.org/
- name: NPM CI
- run: npm install --force
+ run: npm install
- name: Repository build
run: npm run build
@@ -45,7 +45,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Prepare distribution
- run: cp package.json README.md LICENSE CHANGELOG.md CONTRIBUTING.md CODE_OF_CONDUCT.md ./dist
+ run: cp package.json README.md LICENSE.txt CHANGELOG.md CONTRIBUTING.md CODE_OF_CONDUCT.md ./dist
- name: Publish
run: |
diff --git a/.nycrc b/.nycrc
index 72535526..675dcd3d 100644
--- a/.nycrc
+++ b/.nycrc
@@ -5,8 +5,8 @@
"extension": [ ".js" ],
"include": [ "dist/*.js" ],
"exclude": [ "dist/index.js", "dist/_virtual/**/*.js" ],
- "branches": 60,
- "lines": 70,
+ "branches": 50,
+ "lines": 80,
"functions": 70,
"statements": 70
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a252654b..9f571110 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -999,3 +999,12 @@ Errored release
### Fixes
- `useLocalStorage` and `useSessionStorage` no longer return a new `setValue` function everytime `setValue` is called
+
+## [4.0.0] - 2023-03-13
+
+### Breaking Changes
+
+- Removes `index.ts` file from `src` folder
+- Updates dependencies
+- Improves documentation
+- Improves types
diff --git a/HOOK_DOCUMENTATION_TEMPLATE.md b/HOOK_DOCUMENTATION_TEMPLATE.md
index 36b2c3d3..516cbc96 100644
--- a/HOOK_DOCUMENTATION_TEMPLATE.md
+++ b/HOOK_DOCUMENTATION_TEMPLATE.md
@@ -1,6 +1,6 @@
# useYourHookName
--- A short description of your hook --
+A hook that [...]
### π‘ Why?
@@ -9,12 +9,11 @@
### Basic Usage:
```jsx harmony
-import { yourHook } from 'beautiful-react-hooks';
-
+import { yourHook } from 'beautiful-react-hooks';
const YourExample = () => {
/* Your code goes here */
-
+
return null;
};
@@ -26,12 +25,11 @@ const YourExample = () => {
description of the use case
```jsx harmony
-import { yourHook } from 'beautiful-react-hooks';
-
+import { yourHook } from 'beautiful-react-hooks';
const YourUseCase = () => {
/* Your code goes here */
-
+
return null;
};
@@ -41,9 +39,11 @@ const YourUseCase = () => {
### Mastering the hooks
#### β
When to use
-
+
- When it's good to use
#### π When not to use
- When it's not good to use
+
+
diff --git a/LICENSE b/LICENSE.txt
similarity index 100%
rename from LICENSE
rename to LICENSE.txt
diff --git a/README.md b/README.md
index fc868935..bd70f93b 100644
--- a/README.md
+++ b/README.md
@@ -13,15 +13,14 @@ MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.or
- A collection of beautiful (and hopefully useful) React hooks to speed-up your
- components and hooks development
+ A collection of tailor-made React hooks to enhance your development process and make it faster.
@@ -38,13 +37,13 @@ MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.or
## π‘ Why?
-React custom hooks allow to abstract components' business logic into single reusable functions.
-So far, we've found that most of the hooks we've created and therefore shared between our internal projects have quite often a similar gist
-that involves callback references, events and components' lifecycle.
-For this reason we've tried to sum up that gist into `beautiful-react-hooks`: a collection of (*hopefully*) useful React hooks to possibly
-help other companies and professionals to speed up their development process.
-Furthermore, we created a concise yet concrete API having in mind the code readability, focusing to keep the learning curve as lower as
-possible so that the it can be used and shared in bigger teams.
+Custom React hooks allow developers to abstract the business logic of components into single, reusable functions.\
+I have noticed that many of the hooks I have created and shared across projects involve callbacks, references, events, and dealing with the
+component lifecycle.\
+Therefore, I have created `beautiful-react-hooks`, a collection of useful [React hooks](https://beta.reactjs.org/reference/react) that may
+help other developers speed up their development process.\
+Moreover, I have strived to create a concise and practical API that emphasizes code readability, while keeping the learning curve as low as
+possible, making it suitable for larger teams to use and share
**-- Please before using any hook, read its documentation! --**
@@ -57,7 +56,7 @@ possible so that the it can be used and shared in bigger teams.
@@ -76,6 +75,14 @@ by using `yarn`:
$ yarn add beautiful-react-hooks
```
+## Basic usage
+
+importing a hooks is as easy as the following straightforward line:
+
+```ts static
+import useSomeHook from 'beautiful-react-hooks/useSomeHook'
+```
+
## π¨ Hooks
* [useQueryParam](docs/useQueryParam.md)
@@ -127,36 +134,29 @@ $ yarn add beautiful-react-hooks
## Peer dependencies
-Some hooks are built on top of third-party libraries (rxjs, react-router-dom, redux), therefore you will notice those libraries listed as
-peer dependencies. You don't have to install these dependencies unless you directly use those hooks.
+Some hooks are built using third-party libraries (such as rxjs, react-router-dom, redux). As a result, you will see these libraries listed
+as peer dependencies.\
+Unless you are using these hooks directly, you need not install these dependencies.
## Contributing
Contributions are very welcome and wanted.
-To submit your custom hook, please make sure your read our [CONTRIBUTING](./CONTRIBUTING.md) guidelines.
+To submit your custom hook, make sure you have thoroughly read and understood the [CONTRIBUTING](./CONTRIBUTING.md) guidelines.
-**Before submitting** a new merge request, please make sure:
+**Prior to submitting your pull request**: please take note of the following
1. make sure to write tests for your code, run `npm test` and `npm build` before submitting your merge request.
-2. in case you're creating a custom hook, make sure you've added the documentation (*you can possibly use
+2. in case you're creating a custom hook, make sure you've added the documentation (*you may use
the [HOOK_DOCUMENTATION_TEMPLATE](./HOOK_DOCUMENTATION_TEMPLATE.md) to document your custom hook*).
-### Made with
-
-* [React](https://reactjs.org/)
-* [Mocha](https://mochajs.org/)
-* [Chai](https://www.chaijs.com/)
-* [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro)
-* [@testing-library/react-hooks](https://react-hooks-testing-library.com/)
-
----
+## Credits
Icon made by [Freepik](https://www.flaticon.com/authors/freepik) from [www.flaticon.com](https://www.flaticon.com/free-icon/hook_1081812)
diff --git a/docs/Installation.md b/docs/Installation.md
index 5500f09e..bb46c36f 100644
--- a/docs/Installation.md
+++ b/docs/Installation.md
@@ -21,28 +21,40 @@ import useSomeHook from 'beautiful-react-hoks/useSomeHook'
**Please note**: always import your hook from the library as a single module to avoid importing unnecessary hooks and therefore unnecessary
dependencies
+## Peer dependencies
+
+Some hooks are built on top of third-party libraries (rxjs, react-router-dom, redux), therefore you will notice those libraries listed as
+peer dependencies. You don't have to install these dependencies unless you directly use those hooks.
+
## Working with Refs in TypeScript
The documentation of this module is written in JavaScript, so you will see a lot of this:
-```javascript
+```jsx static
import { ref } from 'react';
-const ref = useRef()
+const myCustomHook = () => {
+ const ref = useRef()
+
+ /* your code */
+
+ return ref;
+}
```
If you are in a TypeScript project, you should declare your ref as a `RefObject`. For example:
-```ts
+```ts static
import { ref } from 'react';
-const ref = useRef(null);
+const myCustomHook = () => {
+ const ref = useRef(null);
+
+ /* your code */
+
+ return ref;
+}
```
See [here](https://dev.to/wojciechmatuszewski/mutable-and-immutable-useref-semantics-with-react-typescript-30c9) for information on the
difference between a `MutableRefObject` and a `RefObject`.
-
-## Peer dependencies
-
-Some hooks are built on top of third-party libraries (rxjs, react-router-dom, redux), therefore you will notice those libraries listed as
-peer dependencies. You don't have to install these dependencies unless you directly use those hooks.
diff --git a/docs/Introduction.md b/docs/Introduction.md
index cf9cf30c..632a7329 100644
--- a/docs/Introduction.md
+++ b/docs/Introduction.md
@@ -5,36 +5,35 @@
![npm](https://img.shields.io/npm/v/beautiful-react-hooks)
![GitHub stars](https://img.shields.io/github/stars/beautifulinteractions/beautiful-react-hooks?style=social)
-Beautiful React Hooks is a collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development.
+`beautiful-react-hooks` is a collection of tailor-made [React hooks](https://beta.reactjs.org/reference/react) to enhance your development
+process and make it faster.
## π‘ Why?
-React custom hooks allow abstracting components' business logic into single reusable functions.
-So far, I've found that most of the hooks I've created and therefore shared between my projects have quite often a similar gist that
-involves callback references, events and components' lifecycle.
-For this reason I've tried to sum up that gist into `beautiful-react-hooks`: a collection of (*hopefully*) useful React hooks to possibly
-help other developers to speed up their development process.
-Furthermore, I've tried to create a concise yet concrete API having in mind the code readability, focusing to keep the learning curve as
-lower as possible so that the it can be used and shared in bigger teams.
+Custom React hooks allow developers to abstract the business logic of components into single, reusable functions.
+I have noticed that many of the hooks I have created and shared across projects involve callbacks, references, events, and dealing with the
+component lifecycle.
+Therefore, I have created `beautiful-react-hooks`, a collection of useful [React hooks](https://beta.reactjs.org/reference/react) that may
+help other developers speed up their development process.
+Moreover, I have strived to create a concise and practical API that emphasizes code readability, while keeping the learning curve as low as
+possible, making it suitable for larger teams to use and share
## βοΈ Features
* Concise API
* Small and lightweight
* Easy to learn
-* Functional approach
-* Fully written in JS (although TS types are supported)
-## Peer dependencies
-
-Some hooks are built on top of third-party libraries (rxjs, react-router-dom, redux), therefore you will notice those libraries listed as
-peer dependencies. You don't have to install these dependencies unless you directly use those hooks.
-
-## Imports
+## Basic usage
-Despite having an `index.ts` file, it's recommended importing the hooks from the library in the following fashion to avoid importing
-unnecessary hooks and therefore unnecessary dependencies
+importing a hooks is as easy as the following straightforward line:
```ts static
import useSomeHook from 'beautiful-react-hooks/useSomeHook'
```
+
+## Peer dependencies
+
+Some hooks are built using third-party libraries (such as rxjs, react-router-dom, redux). As a result, you will see these libraries listed
+as peer dependencies.\
+Unless you are using these hooks directly, you need not install these dependencies.
diff --git a/docs/useAudio.md b/docs/useAudio.md
index 01bbcec9..76556806 100644
--- a/docs/useAudio.md
+++ b/docs/useAudio.md
@@ -1,52 +1,100 @@
# useAudio
-Creates element, tracks its state and exposes playback controls.
+Creates an `` element, monitors its state and provides access to playback controls.
### Why? π‘
-- A quick way to use the `Audio` in your React components.
+- A speedy approach to integrating the audio feature into your React component
+- Enhances the readability of components involving the audio feature
### Basic Usage:
```jsx harmony
import { useRef, useState } from 'react';
-import { Button } from 'beautiful-react-ui';
+import { Button, Typography } from 'antd';
+import { PlayCircleFilled, PauseCircleFilled } from '@ant-design/icons';
+
import useAudio from 'beautiful-react-hooks/useAudio';
const UseAudioComponent = () => {
const [state, controls] = useAudio("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", { autoPlay: true });
+ const code = JSON.stringify(state, null, '\t');
+
+ const Actions = [
+ } />,
+ } />,
+
+ Mute
+ ,
+ controls.setVolume(state.volume + 0.1)}>Vol +1 ,
+ controls.setVolume(state.volume - 0.1)}>Vol -1 ,
+ controls.seek(state.currentTime + 10)}>+10 secs ,
+ controls.seek(state.currentTime - 10)}>-10 secs
+ ]
return (
-
- {JSON.stringify(state, null, 2)}
-
-
- Play
-
-
- Pause
-
-
-
- Mute
-
-
- Unmute
-
-
- controls.setVolume(.1)}>Volume: 10%
- controls.setVolume(.5)}>Volume: 50%
- controls.setVolume(1)}>Volume: 100%
-
- controls.seek(state.currentTime + 10)}>
- Jump 10 seconds
-
- controls.seek(state.currentTime - 10)}>
- Jump -10 seconds
-
+
+
+
+ {code}
+
+
);
};
```
+
+
+### Types
+
+```typescript static
+import { type MutableRefObject } from 'react';
+/**
+ * The useAudio hook wraps the Audio API and provides a set of controls to manage the audio
+ */
+export declare const useAudio: (src: string, options?: UseAudioOptions) => [AudioState, Readonly, MutableRefObject];
+type UseAudioPreloadType = 'auto' | 'metadata' | 'none';
+/**
+ * The interface for the state of the useAudio hook
+ */
+export interface AudioState {
+ loop: boolean;
+ muted: boolean;
+ volume: number;
+ duration: number;
+ autoPlay: boolean;
+ isPlaying: boolean;
+ preload?: UseAudioPreloadType;
+ currentTime: number;
+ playbackRate: number;
+ isSrcLoading: boolean | undefined;
+}
+/**
+ * The interface for the options of the useAudio hook
+ */
+export interface UseAudioOptions {
+ loop?: boolean;
+ muted?: boolean;
+ volume?: number;
+ autoPlay?: boolean;
+ preload?: UseAudioPreloadType;
+ playbackRate?: number;
+}
+/**
+ * The interface for the controls of the useAudio hook
+ */
+export interface AudioControls {
+ play: () => void;
+ mute: () => void;
+ pause: () => void;
+ unmute: () => void;
+ seek: (time: number) => void;
+ onError: (onError: ((error: Error) => void)) => void;
+ setVolume: (volume: number) => void;
+}
+export default useAudio;
+
+```
+
\ No newline at end of file
diff --git a/docs/useConditionalTimeout.md b/docs/useConditionalTimeout.md
index 783c1106..b4c49e0e 100644
--- a/docs/useConditionalTimeout.md
+++ b/docs/useConditionalTimeout.md
@@ -1,32 +1,50 @@
# useConditionalTimeout
-An async-utility hook that accepts a callback `function`, a `delay time` (*in milliseconds*) and a `condition`, then delays the execution of
-the given function by the defined time when the condition is verified.
+An asynchronous hook which takes in three parameters: a "callback", a "delay time" (in milliseconds), and a boolean value known as "
+condition".\
+It then postpones the execution of the given callback by the specified delay time, only when the provided condition changes to `true`
### π‘ Why?
-- to start a timeout only after a given condition is verified;
-- takes care of performing the given callback regardless the component re-renders;
-- cancels the timeout when component unmount (or not, depends by the defined options) and/or the given condition verifies;
+- To start a timeout only after a certain condition has been confirmed;
+- Handles the executing of the provided callback despite the component's re-rendering;
+- Terminates the timeout when the component unmounts (or not, depending on the specified options) and/or when the provided condition is
+ confirmed;
### Basic Usage:
```jsx harmony
import { useState } from 'react';
-import { Button } from 'beautiful-react-ui';
+import { Button, Space, Typography } from 'antd';
+
import useConditionalTimeout from 'beautiful-react-hooks/useConditionalTimeout';
const ConditionalDelayedContentComponent = () => {
const [condition, setCondition] = useState(false);
const [showContent, setShowContent] = useState(false);
+
useConditionalTimeout(() => {
setShowContent(true)
}, 2000, condition);
+ const Actions = [
+ setCondition(true)} disabled={condition} loading={condition && !showContent}>
+ {condition ? 'Timer started' : 'Start the timer'}…
+
+ ]
+
return (
-
- setCondition(true)}> Start a 2 seconds timeout
- {showContent && π°
}
+
+
+
+ Click on the following button to change the condition that triggers the 2 seconds timeout to true
+
+
+ After timeout is elapsed a content is displayed
+
+ {showContent && π°
}
+
+
)
};
@@ -35,11 +53,12 @@ const ConditionalDelayedContentComponent = () => {
### State & clear method:
-The hook returns the state of the timeout (a boolean, cleared/not cleared) and a method to possibly clear it.
+The hook will return the state of the timeout (either cleared or not cleared) and a function that may be used to clear it.
```jsx harmony
import { useState } from 'react';
-import { Button, Paragraph } from 'beautiful-react-ui';
+import { Button, Typography } from 'antd';
+
import useConditionalTimeout from 'beautiful-react-hooks/useConditionalTimeout';
const ConditionalDelayedContentComponent = () => {
@@ -49,14 +68,18 @@ const ConditionalDelayedContentComponent = () => {
setShowContent(true)
}, 5000, condition);
+ const Actions = [
+ setCondition(true)} disabled={condition}>Start a 5 seconds timeout
+ ]
+
return (
-
- Content will show after 5 second starting from the following button click
- setCondition(true)}>Start a 5 seconds timeout
+
+ Content will show after 5 second starting from the following button click
{showContent && π°
}
- {!isCleared && Cancel timeout }
- {isCleared && Cleared }
- )
+ {!isCleared && !showContent && Cancel timeout }
+ {isCleared && Cleared }
+
+ )
};
@@ -64,7 +87,7 @@ const ConditionalDelayedContentComponent = () => {
### Options:
-`useConditionalTimeout` might accept a options object provided as eventual parameter.
+The third parameter is an optional object of options
#### cancelOnUnmount:
@@ -74,7 +97,7 @@ Defines whether the timeout should be cleared on unmount.
```jsx harmony
import { useState } from 'react';
-import { Button } from 'beautiful-react-ui';
+import { Button } from 'antd';
import useConditionalTimeout from 'beautiful-react-hooks/useConditionalTimeout';
const ConditionalDelayedContentComponent = () => {
@@ -87,8 +110,8 @@ const ConditionalDelayedContentComponent = () => {
}, 5000, condition, options);
return (
-
- setCondition(true)}>Start a 5 seconds timeout
+
+ setCondition(true)}>Start a 5 seconds timeout
{showContent && π°
}
)
};
@@ -98,16 +121,16 @@ const ConditionalDelayedContentComponent = () => {
#### cancelOnConditionChange:
-Defines whether the timeout should be cleared when the condition change.
+Defines whether the timeout should be cleared when the condition changes.
-In this example nothing will happen because when clicking on the button, 2 instance of useConditionalTimeout will be performed, and one of
-them will change the condition.
+In this example, clicking on the button will not trigger any action as there are two instances of useConditionalTimeout, and one of them
+will modify the condition.
**default**: `true`
```jsx harmony
import { useState } from 'react';
-import { Button } from 'beautiful-react-ui';
+import { Button } from 'antd';
import useConditionalTimeout from 'beautiful-react-hooks/useConditionalTimeout';
const ConditionalDelayedContentComponent = () => {
@@ -117,13 +140,14 @@ const ConditionalDelayedContentComponent = () => {
useConditionalTimeout(() => {
setShowContent(true)
}, 5000, condition);
+
useConditionalTimeout(() => {
setCondition(false)
}, 2000, condition);
return (
-
- setCondition(true)}>Start a 5 seconds timeout
+
+ setCondition(true)}>Start a 5 seconds timeout
{showContent && π°
}
)
};
@@ -135,4 +159,24 @@ const ConditionalDelayedContentComponent = () => {
#### β
When to use
-- If there's the necessity to run a callback after a certain time and only when a certain condition is verified.
+- If it is necessary to execute a callback after a specific duration and only when a specific condition has been verified.
+
+
+### Types
+
+```typescript static
+import { type GenericFunction } from './shared/types';
+/**
+ * An async-utility hook that accepts a callback function and a delay time (in milliseconds), then delays the
+ * execution of the given function by the defined time from when the condition verifies.
+ */
+declare const useConditionalTimeout: (fn: TCallback, milliseconds: number, condition: boolean, options?: UseConditionalTimeoutOptios) => UseConditionalTimeoutReturn;
+export interface UseConditionalTimeoutOptios {
+ cancelOnUnmount?: boolean;
+ cancelOnConditionChange?: boolean;
+}
+export type UseConditionalTimeoutReturn = [boolean, () => void];
+export default useConditionalTimeout;
+
+```
+
\ No newline at end of file
diff --git a/docs/useCookie.md b/docs/useCookie.md
index c5c2eee9..32dd510b 100644
--- a/docs/useCookie.md
+++ b/docs/useCookie.md
@@ -1,32 +1,34 @@
# useCookie
-A hook for storing, updating and deleting values into [CookieStore](https://developer.mozilla.org/en-US/docs/Web/API/CookieStore).
+A hook that facilitates the storage, updating, and deletion of values within
+the [CookieStore](https://developer.mozilla.org/en-US/docs/Web/API/CookieStore).
### π‘ Why?
-- A quick way to use the `CookieStore` in your React components.
+- A quick and safe way to access the `CookieStore` in your React components.
+- Improves readability of React components accessing the `CookieStore
### Basic Usage:
```jsx harmony
import { useCallback } from 'react';
-import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
-import useCookie from 'beautiful-react-hooks/useCookie';
+import { Typography, Tag, Button } from 'antd';
+
+import useCookie from 'beautiful-react-hooks/useCookie';
const UseCookieExample = () => {
- const {
- onError,
- cookieValue,
- deleteCookie,
- updateCookie
- } = useCookie('cookie-key', { secure: false, path: '/', defaultValue: 'default-value' });
+ const { onError, cookieValue, deleteCookie, updateCookie } = useCookie('cookie-key', {
+ secure: false,
+ path: '/',
+ defaultValue: 'default-value'
+ });
onError((error) => {
console.log(error)
alert(error.message)
})
-
+
const updateButtonClick = useCallback(() => {
updateCookie('new-cookie-value')
}, [])
@@ -35,18 +37,23 @@ const UseCookieExample = () => {
deleteCookie()
}, [])
+ const Actions = [
+
+ Update the cookieStore
+ ,
+
+ Clear the cookieStore
+
+ ]
+
return (
-
- Click on the button to update or clear from the cookieStore
- {cookieValue || ''}
-
-
- update the cookieStore
-
-
-
- Clear the cookieStore
-
+
+
+ Click on the button to update or clear the cookieStore
+
+
+ {cookieValue || 'no value'}
+
)
};
@@ -58,8 +65,41 @@ const UseCookieExample = () => {
#### β
When to use
-- When you need to get/set values from the `cookieStore`
+- When you need to CRUD values from the `CookieStore`
#### π When not to use
-- This hook(cookieStore) can't be used in server-side and http website.
+- in server-only components (during SSR)
+
+
+### Types
+
+```typescript static
+import { type CallbackSetter } from './shared/types';
+declare const useCookie: (key: string, options?: UseCookieOptions) => Readonly;
+export declare enum CookieSameSite {
+ STRICT = "strict",
+ LAX = "lax",
+ NONE = "none"
+}
+interface CookieStoreDeleteOptions {
+ name?: string;
+ domain?: string;
+ path?: string;
+}
+interface CookieBase extends CookieStoreDeleteOptions {
+ sameSite?: CookieSameSite;
+}
+export interface UseCookieOptions extends CookieBase {
+ defaultValue?: string;
+}
+export interface UseCookieReturn {
+ cookieValue?: string;
+ updateCookie: (nextValue: string) => Promise;
+ deleteCookie: () => Promise;
+ onError: CallbackSetter;
+}
+export default useCookie;
+
+```
+
\ No newline at end of file
diff --git a/docs/useDarkMode.md b/docs/useDarkMode.md
index dbe09172..782c37fb 100644
--- a/docs/useDarkMode.md
+++ b/docs/useDarkMode.md
@@ -1,44 +1,39 @@
# useDarkMode
--- This hook handle all logic required to add a βΎ dark mode toggle to your website --
+A hook that manages all the necessary operations to incorporate a toggle switch for dark and light modes on your website
### π‘ Why?
-- SSR safe,
-- Keep information about dark mode in local storage
-- Return a few functions allows you to change dark mode state
-- Read information about dark mode from user's operating system `prefers-color-scheme`
+- Keep information about dark/light mode consistent and in sync across sessions using localStorage
+- Return the methods that allows you to change into dark/light mode
+- Safely read information about the dark/light mode from user's operating system using `prefers-color-scheme`
### Basic Usage:
```jsx harmony
-import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
-import useDarkMode from 'beautiful-react-hooks/useDarkMode';
+import { Typography, Tag, Button } from 'antd';
+
+import useDarkMode from 'beautiful-react-hooks/useDarkMode';
const UseDarkModeExample = () => {
- const {
- toggle,
- enable,
- disable,
- isDarkMode
- } = useDarkMode();
-
+ const { toggle, enable, disable, isDarkMode } = useDarkMode();
+
+ const Actions = [
+
+ Enable dark mode
+ ,
+
+ Disable dark mode
+ ,
+
+ Toggle dark mode
+
+ ]
+
return (
-
- Click on the buttons to update isDarkMode flag
- isDarkMode: {isDarkMode ? 'true' : 'false'}
-
-
- Enable dark mode
-
-
-
- Disable dark mode
-
-
-
- Toggle dark mode
-
+
+ Click on the buttons to update isDarkMode flag
+ isDarkMode: {isDarkMode ? 'true' : 'false'}
);
};
@@ -48,10 +43,23 @@ const UseDarkModeExample = () => {
### Mastering the hooks
-#### β
When to use
-
-- When you need to handle dark/light mode logic in your app,
-
#### π When not to use
-- This hook does not support SSR,
+- in server-only components (during SSR)
+
+
+### Types
+
+```typescript static
+export declare const LOCAL_STORAGE_KEY = "beautiful-react-hooks-is-dark-mode";
+declare const useDarkMode: (defaultValue?: boolean, localStorageKey?: string) => Readonly;
+export interface UseDarkModeReturn {
+ isDarkMode: boolean;
+ toggle: () => void;
+ enable: () => void;
+ disable: () => void;
+}
+export default useDarkMode;
+
+```
+
\ No newline at end of file
diff --git a/docs/useDebouncedCallback.md b/docs/useDebouncedCallback.md
index f536f127..6d85f804 100644
--- a/docs/useDebouncedCallback.md
+++ b/docs/useDebouncedCallback.md
@@ -1,17 +1,21 @@
# useDebouncedCallback
-Takes a `function` and returns a new memoized version of that function that delays its invoking by the defined time. If time is not defined,
-its default value will be 250ms.
+A hook that accepts a `function` parameter and produces a new memoized variant of that function which postpones its invocation by the
+specified duration.\
+In case the duration is not specified, it will be set to the default value of 600ms.\
+
+This hook is built on top of the `lodash.debounce` function. For further details, kindly refer to
+the [Lodash documentation](https://lodash.com/docs/#debounce).
### Why? π‘
-- Controls how many times we allow a function to be executed over time regardless the number of renders the component is performing
+- To take full control over frequency at which a function can execute, independent of the number of renders performed by the component
### Basic Usage
```jsx harmony
import { useEffect, useState } from 'react';
-import { Paragraph } from 'beautiful-react-ui';
+import { Typography, Alert, Space, Tag } from 'antd';
import useDebouncedCallback from 'beautiful-react-hooks/useDebouncedCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -36,9 +40,15 @@ const DebouncedFnComponent = () => {
});
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -53,7 +63,7 @@ under the hood, you can possibly define the callback dependencies.
```jsx harmony
import { useState } from 'react';
-import { Paragraph } from 'beautiful-react-ui';
+import { Typography, Alert, Space, Tag } from 'antd';
import useDebouncedCallback from 'beautiful-react-hooks/useDebouncedCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -71,9 +81,15 @@ const DebouncedFnComponent = (props) => {
onWindowResize(onWindowResizeHandler);
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -87,7 +103,7 @@ A custom debounce time can be easily defined as follows (500ms)
```jsx harmony
import { useState } from 'react';
-import { Paragraph } from 'beautiful-react-ui';
+import { Typography, Alert, Space, Tag } from 'antd';
import useDebouncedCallback from 'beautiful-react-hooks/useDebouncedCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -106,9 +122,15 @@ const DebouncedFnComponent = (props) => {
onWindowResize(onWindowResizeHandler);
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -123,7 +145,7 @@ few options to customise its behaviour.
```jsx harmony
import { useState } from 'react';
-import { Paragraph } from 'beautiful-react-ui';
+import { Typography, Alert, Space, Tag } from 'antd';
import useDebouncedCallback from 'beautiful-react-hooks/useDebouncedCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -146,9 +168,15 @@ const DebouncedFnComponent = () => {
onWindowResize(onWindowResizeHandler);
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -158,12 +186,29 @@ const DebouncedFnComponent = () => {
#### β
Pro tip:
-To deep understanding the differences between `throttle` and `debounce`, what they are and when to use this functions please
+To deep understanding the differences between `throttle` and `debounce`, what they are and when to use them please
read "[Debouncing and Throttling Explained Through Examples](https://css-tricks.com/debouncing-throttling-explained-examples/)"
by [David Corbacho](https://twitter.com/dcorbacho)
-### Mastering the hook
-
-#### β
When to use
+
+### Types
+
+```typescript static
+///
+import { type DependencyList } from 'react';
+import { type GenericFunction } from './shared/types';
+export interface DebounceOptions {
+ leading?: boolean | undefined;
+ maxWait?: number | undefined;
+ trailing?: boolean | undefined;
+}
+/**
+ * Accepts a function and returns a new debounced yet memoized version of that same function that delays
+ * its invoking by the defined time.
+ * If time is not defined, its default value will be 250ms.
+ */
+declare const useDebouncedCallback: (fn: TCallback, dependencies?: DependencyList, wait?: number, options?: DebounceOptions) => import("lodash").DebouncedFunc;
+export default useDebouncedCallback;
-- The classic example would be an API call that would be performed when typing on a search field
+```
+
\ No newline at end of file
diff --git a/docs/useDefaultedState.md b/docs/useDefaultedState.md
index ef00c5ae..8ffa5ec1 100644
--- a/docs/useDefaultedState.md
+++ b/docs/useDefaultedState.md
@@ -1,32 +1,35 @@
# useDefaultedState
-Works as `useState` except it accepts a `defaultValue` and possibly an `initialState`, then makes sure the returned state
-is always `defaultValue` when `null` or `undefined`.
-
+A hook that functions similar to `useState`, with the added capability to receive a defaultValue and potentially an initialState.\
+This hook guarantees that the state returned is always set to defaultValue in the event of it being null or undefined.
+
### Why? π‘
-- Avoid side-effects by ensuring a safe state
+- Avoids side-effects by ensuring a default state value
### Basic Usage:
```jsx harmony
-import { Button } from 'beautiful-react-ui';
-import useDefaultedState from 'beautiful-react-hooks/useDefaultedState';
+import { Typography, Button } from 'antd';
+import useDefaultedState from 'beautiful-react-hooks/useDefaultedState';
/**
-* useDefaultedState example component
-*/
-const DefaultedStateExample = () => {
- const placeholder = { name: 'John Doe' };
- const data = { name: 'Antonio RΓΉ' };
- const [user, setUser] = useDefaultedState(placeholder, data);
-
- return (
-
- The user name is: {user.name}
- setUser()}>Change to undefined
-
- );
+ * useDefaultedState example component
+ */
+const DefaultedStateExample = () => {
+ const placeholder = { name: 'John Doe' };
+ const data = { name: 'Antonio RΓΉ' };
+ const [user, setUser] = useDefaultedState(placeholder, data);
+
+ const Actions = [
+ setUser()}>Change to 'undefined' ,
+ ]
+
+ return (
+
+ The user name is: {user.name}
+
+ );
};
@@ -35,5 +38,18 @@ const DefaultedStateExample = () => {
### Mastering the hook
#### β
When to use
-
-- When in need of a safe state that should never be null or undefined
+
+- If you require a secure state that must never be null or undefined
+
+
+### Types
+
+```typescript static
+/**
+ * Returns a safe state by making sure the given value is not null or undefined
+ */
+declare const useDefaultedState: (defaultValue: TValue, initialState?: TValue | undefined) => [TValue, (nextState: TValue) => void];
+export default useDefaultedState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useDidMount.md b/docs/useDidMount.md
index 4bc4d291..727a85d4 100644
--- a/docs/useDidMount.md
+++ b/docs/useDidMount.md
@@ -1,34 +1,34 @@
# useDidMount
-Accepts a function to be performed when the component did mount.
+A hook that takes in a function to execute when the component has finished mounting.
### Why? π‘
-- takes care of performing a callback when the component mount
-- It's as a shortcut to `useEffect(onMount, [])`
+- takes care of performing a callback when the component mounts
+- Is intended as a shortcut to `useEffect(onMount, [])`
### Basic Usage:
```jsx harmony
import { useState } from 'react';
-import { Paragraph } from 'beautiful-react-ui';
-import useDidMount from 'beautiful-react-hooks/useDidMount';
+import { Typography } from 'antd';
+import useDidMount from 'beautiful-react-hooks/useDidMount';
const ComponentDidMount = () => {
- const [mounted, setIsMounted] = useState(false);
-
- useDidMount(() => {
+ const [mounted, setIsMounted] = useState(false);
+
+ useDidMount(() => {
const timeout = setTimeout(() => {
setIsMounted(true);
clearTimeout(timeout);
}, 1000);
- });
-
- return (
-
- {mounted && (Component did mount! )}
-
- );
+ });
+
+ return (
+
+ {mounted && (Component did mount! )}
+
+ );
};
@@ -36,33 +36,33 @@ const ComponentDidMount = () => {
### Callback setter syntax:
-if the first parameter is not provided, the returned function (*a handler setter*) can be used to
-set the `useDidMount` handler, as long as it is immediately invoked.
+if the first parameter is not provided, the returned function (*a callback setter*) can be used to set the `useDidMount` handler, as long as
+it is immediately invoked.
-**Please note**: the returned handler setter is meant to change the value of the callback reference only, it does not
-cause the component rerender nor should not be invoked asynchronously.
+**Please note**: the returned callback setter is meant to change the value of the callback reference only, it does not cause the component
+rerender nor should not be invoked asynchronously.
```jsx harmony
import { useState } from 'react';
-import { Paragraph } from 'beautiful-react-ui';
-import useDidMount from 'beautiful-react-hooks/useDidMount';
+import { Typography } from 'antd';
+import useDidMount from 'beautiful-react-hooks/useDidMount';
const ComponentDidMount = () => {
- const [mounted, setIsMounted] = useState(false);
- const onMount = useDidMount();
-
- onMount(() => {
+ const [mounted, setIsMounted] = useState(false);
+ const onMount = useDidMount();
+
+ onMount(() => {
const timeout = setTimeout(() => {
setIsMounted(true);
clearTimeout(timeout);
}, 1000);
- });
-
- return (
-
- {mounted && (Component did mount! )}
-
- );
+ });
+
+ return (
+
+ {mounted && (Component did mount! )}
+
+ );
};
@@ -81,10 +81,24 @@ by [Dan Abramov](https://twitter.com/dan_abramov)
### Mastering the hook
#### β
When to use
-
-- When in need of performing a function after the component did mount
+
+- When in need of performing a function after the component mounts
#### π When not to use
- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
-- If using the handler setter, it should not be used asynchronously but immediately invoked
+- If using the callback setter, it should not be used asynchronously but immediately invoked
+
+
+### Types
+
+```typescript static
+import { type GenericFunction, type Noop } from './shared/types';
+/**
+ * Returns a callback setter for a function to be performed when the component did mount.
+ */
+declare const useDidMount: (callback?: TCallback | undefined) => import("./shared/types").CallbackSetter;
+export default useDidMount;
+
+```
+
\ No newline at end of file
diff --git a/docs/useDrag.md b/docs/useDrag.md
index 3e5d0c37..2ac6e3c5 100644
--- a/docs/useDrag.md
+++ b/docs/useDrag.md
@@ -1,11 +1,12 @@
# useDrag
-Accepts an HTML Element ref then makes it draggable. Returns a boolean reporting whether the element in being dragged or not.
+A hook that receives a reference to an HTML Element (using React's useRef) and enables it to be dragged.\
+The hook returns a boolean value indicating whether the element is currently being dragged or not.
### Why? π‘
-- takes care of adding the drag-related events listeners to the defined target
-- takes care of cleaning the listener when the component will unmount
+- takes care of attaching drag-related event listeners to the specified target
+- takes care of emoving the listener when the component is unmounted.
- allow to easily implement draggable business logic
### Basic Usage:
@@ -21,7 +22,7 @@ const MyComponent = () => {
const isDragged = useDrag(ref);
return (
-
+
Draggable item...
{isDragged &&
is being dragged }
@@ -48,7 +49,7 @@ const MyComponent = () => {
});
return (
-
+
Draggable item...
{isDragged &&
is being dragged }
@@ -74,7 +75,7 @@ const MyComponent = () => {
});
return (
-
+
Draggable item...
{isDragged &&
is being dragged }
@@ -90,4 +91,22 @@ const MyComponent = () => {
#### β
When to use
-- When in need of implementing basic drag-related business logic
+- If you require basic drag-related business logic
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+export interface UseDragOptions {
+ dragImage?: string;
+ dragImageXOffset?: number;
+ dragImageYOffset?: number;
+ transfer?: string | number | Record
;
+ transferFormat?: string;
+}
+declare const useDrag: (targetRef: RefObject, options?: UseDragOptions) => boolean;
+export default useDrag;
+
+```
+
\ No newline at end of file
diff --git a/docs/useDragEvents.md b/docs/useDragEvents.md
index 1484677e..c75d0898 100644
--- a/docs/useDragEvents.md
+++ b/docs/useDragEvents.md
@@ -1,22 +1,22 @@
# useDragEvents
-Returns an object of handler setters to handle the drag-related events. It accepts a DOM ref representing the events target (where attach
-the events to).
+A hook that provides a collection of functions designed to simplify the management of drag-related events.\
+It takes a reference to target element where the events are to be attached.\
+This hook facilitates the handling of drag events, making it easier for developers to incorporate drag-and-drop functionality into their web
+applications.
-Returned handler setters: `onDrag`, `onDrop`, `onDragEnter`, `onDragEnd`, `onDragExit`, `onDragLeave`, `onDragOver`, `onDragStart`;
-
-**Please note:** the returned handler setters should invoked immediately in the function component's body, do not try to call this functions
-asynchronously.
+**Please note:** the returned callback setters should be invoked immediately in the function component's body, do not try to call this
+functions asynchronously.
### Why? π‘
-- takes care of adding the drag-related events listeners to the defined target
-- takes care of cleaning the listener when the component will unmount
-- allow to perform abstractions on drag-related events
+- Takes care of attaching the drag-related event listeners to the specified target element
+- Automatically removes the event listeners when the component is unmounted
+- Enables the ability to abstract the handling of drag-related events
### Basic Usage:
-Provide a DOM ref as first parameter to `useDragEvents`
+Provide a DOM element ref as first parameter to `useDragEvents`
```jsx harmony
import { useRef, useState } from 'react';
@@ -36,7 +36,7 @@ const MyComponent = () => {
});
return (
-
+
Draggable item...
{isDragged &&
is being dragged }
@@ -50,8 +50,7 @@ const MyComponent = () => {
### Draggable attribute:
-The second argument of `useDragEvents` defines whether to set the `draggable` attribute to the target element. By default, this is set
-to `true`.
+the second parameter determines whether the target element should have the `draggable` attribute set. By default, this is set to `true`.
**Please note**:
@@ -87,7 +86,7 @@ const MyComponent = () => {
});
return (
-
+
Draggable item...
{isDragged &&
is being dragged }
@@ -112,14 +111,11 @@ const MyComponent = () => {
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code.
-- Absolutely avoid using `useDragEvents` handler setters to replace the standard drag handler props.
-- `useDragEvents` is meant to be used to abstract more complex hooks that need to control the drag n drop, for example:
- the drag-around hook.
-- Using `useDragEvents` handlers instead of the classic props approach it's just as bad as it sounds since you'll lose the React
- SyntheticEvent performance boost.
-- If you were doing something like the following, please keep doing it:
+- Using the returned callback setter asynchronously won't have any effect and could introduce bugs into your code, so it should be avoided.
+- Standard drag handler props (like `onDragStart`) should not be replaced with useDragEvents callback setters.
+- useDragEvents is designed to be used for more complex hooks that require control over drag and drop.
+- Replacing classic props with useDragEvents handlers can lead to a loss in performance due to the lack of React SyntheticEvent support.
+- If you were already using a method similar to the following, it is recommended to continue doing so:
```jsx harmony static noedit
const MyComponent = (props) => {
@@ -129,4 +125,33 @@ const MyComponent = (props) => {
);
};
-```
+```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+import { type CallbackSetter } from './shared/types';
+export interface UseDragEventsResult {
+ onDrag: CallbackSetter
;
+ onDrop: CallbackSetter;
+ onDragEnter: CallbackSetter;
+ onDragEnd: CallbackSetter;
+ onDragExit: CallbackSetter;
+ onDragLeave: CallbackSetter;
+ onDragOver: CallbackSetter;
+ onDragStart: CallbackSetter;
+}
+/**
+ * Returns an object of callback setters to handle the drag-related events.
+ * It accepts a DOM ref representing the events target (where attach the events to).
+ *
+ * Returned callback setters: `onDrag`, `onDrop`, `onDragEnter`, `onDragEnd`, `onDragExit`, `onDragLeave`,
+ * `onDragOver`, `onDragStart`;
+ */
+declare const useDragEvents: (targetRef: RefObject, isDraggable?: boolean) => Readonly;
+export default useDragEvents;
+
+```
+
\ No newline at end of file
diff --git a/docs/useDropZone.md b/docs/useDropZone.md
index bd0e6794..8d16a6f6 100644
--- a/docs/useDropZone.md
+++ b/docs/useDropZone.md
@@ -1,12 +1,12 @@
# useDropZone
-Accepts an HTML Element ref then makes it a drop-zone receiving data from dragged object.
+A hook that receives an HTML Element ref and transforms it into a drop-zone capable of accepting data from a dragged object
### Why? π‘
-- takes care of adding the drop-related events listeners to the defined target
-- takes care of cleaning the listener when the component will unmount
-- allow to easily implement drop-related business logic
+- Handles the addition of drop-related event listeners to the specified target
+- Cleans up the listener upon component unmounting
+- Facilitates the implementation of drop-related business logic
### Basic Usage:
@@ -31,7 +31,7 @@ const MyComponent = () => {
});
return (
-
+
{!isDragged &&
Drag to send data }
{isDragged &&
is being dragged }
@@ -51,18 +51,15 @@ const MyComponent = () => {
#### β
When to use
-- When in need of implementing basic drop-related business logic such as file drop
+- If in need to abstract some drag-n-drop related logic into a custom hooks
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code.
-- Absolutely avoid using `onDrop` handler setters to replace the standard drop handler props.
-- `useDropZone` is meant to be used to abstract more complex hooks that need to control the drag n drop, for example:
- the drag-around hook.
-- Using `useDropZone` handlers instead of the classic props approach it's just as bad as it sounds since you'll lose the React
- SyntheticEvent performance boost.
-- If you were doing something like the following, please keep doing it:
+- Using the returned callback setter asynchronously won't have any effect and could introduce bugs into your code, so it should be avoided.
+- Standard drag handler props (like `onDragStart`) should not be replaced with useDragEvents callback setters.
+- useDragEvents is designed to be used for more complex hooks that require control over drag and drop.
+- Replacing classic props with useDragEvents handlers can lead to a loss in performance due to the lack of React SyntheticEvent support.
+- If you were already using a method similar to the following, it is recommended to continue doing so:
```jsx harmony static noedit
const MyComponent = (props) => {
@@ -72,4 +69,20 @@ const MyComponent = (props) => {
);
};
-```
+```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+import { type CallbackSetter } from './shared/types';
+export interface UseDropZoneResult {
+ readonly isOver: boolean;
+ readonly onDrop: CallbackSetter
;
+}
+declare const useDropZone: (targetRef: RefObject) => Readonly;
+export default useDropZone;
+
+```
+
\ No newline at end of file
diff --git a/docs/useEvent.md b/docs/useEvent.md
index e0a92518..b7c528ec 100644
--- a/docs/useEvent.md
+++ b/docs/useEvent.md
@@ -1,18 +1,18 @@
# useEvent
-Accepts the reference to an HTML Element and an event name then performs the necessary operations to listen to the event when fired from
-that HTML Element.
+A hook that allows you to specify an HTML element and an event name. It sets up a listener so that when that event happens on that element,
+your code will be notified and can take action. Essentially, it lets you "listen" for events on a specific HTML element
### Why? π‘
-- takes care of adding a listener for the event to the provided target ref
-- takes care of clearing the listener when the component unmounts
+- Automatically adds the event listener to the element, so you don't have to do it manually
+- Automatically removes the event listener when the component unmounts
### Basic Usage:
-`useEvents` returns a handler setter for the defined event to be immediately invoked.
+`useEvents` returns a callback setter for the defined event to be immediately invoked.
-**Please note**: the handler setter is only meant to change the callback reference, it does not cause the component rerender unless
+**Please note**: the callback setter is only meant to change the callback reference, it does not cause the component rerender unless
differently specified in the function's body. It's not invoked asynchronously
```jsx harmony
@@ -29,11 +29,11 @@ const TestComponent = () => {
});
return (
-
-
- Click on this text to increase the number of clicks: {clicksNo}
-
-
+
+
+ Click on this text to increase the number of clicks: {clicksNo}
+
+
);
};
@@ -63,11 +63,11 @@ const TestComponent = () => {
});
return (
-
-
- Click on this text to increase the number of clicks: {clicksNo}
-
-
+
+
+ Click on this text to increase the number of clicks: {clicksNo}
+
+
);
};
@@ -84,5 +84,20 @@ const TestComponent = () => {
- When you can archive the same result by using a callback, **please remember listening/firing events directly to/from HTMLElement(s) in
React is considered an anti-pattern**
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code
+- You can't use the returned callback setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs
+ in your code
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Accepts the reference to an HTML Element and an event name then performs the necessary operations to listen to the event
+ * when fired from that HTML Element.
+ */
+declare const useEvent: (ref: RefObject, eventName: string, options?: AddEventListenerOptions) => import("./shared/types").CallbackSetter;
+export default useEvent;
+
+```
+
\ No newline at end of file
diff --git a/docs/useGeolocation.md b/docs/useGeolocation.md
index ab7a9d9e..34575a48 100644
--- a/docs/useGeolocation.md
+++ b/docs/useGeolocation.md
@@ -1,20 +1,24 @@
# useGeolocation
-Returns an array where the first item is the geolocation state from [useGeolocationState](./useGeolocationState.md)
-and the second one is an object of handler setters from the [useGeolocationEvents](./useGeolocationEvents.md).
+A hook that does the job of two - now that's efficiency! This nifty little function returns an array with two elements: the first being the
+geolocation state from our trusty [useGeolocationState](./useGeolocationState) hook, and the second being an object of callback setters
+from [useGeolocationEvents](./useGeolocationEvents).
It is intended as a shortcut to those hooks.
### Why? π‘
-- allow to easily access the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API)
-- takes care of adding the geolocation events listeners
-- takes care of cleaning the listener when the component will unmount
-- allow to perform abstractions on geolocation related events
+- facilitates streamlined access to
+ the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API), which allows for
+ geolocation tracking and position updates
+- manages the addition of geolocation event listeners, ensuring that events related to the user's location are properly handled.
+- automatically cleans up the event listener when the component is unmounted, preventing potential memory leaks and optimizing performance
+- enables the abstraction of geolocation-related events, allowing for more flexible and scalable code implementation
### Basic Usage:
```jsx harmony
+import { Typography } from 'antd';
import useGeolocation from 'beautiful-react-hooks/useGeolocation';
const PositionReporter = () => {
@@ -25,14 +29,14 @@ const PositionReporter = () => {
});
return (
-
- The current position is:
- {geoState.isRetrieving && (Retrieving position...
)}
- {geoState.isSupported && geoState.position && [
- Lat: {geoState.position.coords.latitude}
,
- Lng: {geoState.position.coords.longitude}
- ]}
-
+
+ The current position is:
+ {geoState.isRetrieving && (Retrieving position... )}
+ {geoState.isSupported && geoState.position && [
+ Lat: {geoState.position.coords.latitude} ,
+ Lng: {geoState.position.coords.longitude}
+ ]}
+
);
};
@@ -44,6 +48,7 @@ const PositionReporter = () => {
Before using, please read about the [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions)
```jsx harmony
+import { Typography } from 'antd';
import useGeolocation from 'beautiful-react-hooks/useGeolocation';
const PositionReporter = () => {
@@ -58,14 +63,14 @@ const PositionReporter = () => {
});
return (
-
- The current position is:
- {geoState.isRetrieving && (Retrieving position...
)}
- {geoState.isSupported && geoState.position && [
- Lat: {geoState.position.coords.latitude}
,
- Lng: {geoState.position.coords.longitude}
- ]}
-
+
+ The current position is:
+ {geoState.isRetrieving && (Retrieving position... )}
+ {geoState.isSupported && geoState.position && [
+ Lat: {geoState.position.coords.latitude} ,
+ Lng: {geoState.position.coords.longitude}
+ ]}
+
);
};
@@ -76,9 +81,26 @@ const PositionReporter = () => {
#### β
When to use
-- If in need to easily access the Geolocation API.
+- Use this hook when you require effortless access to the Geolocation API
#### π What not to do
-- Don't use this hook to try to guess the user's device capabilities
-- Don't access the geolocation state before checking the `isSupported` flag
+- Do not utilize this hook to speculate the user's device capabilities.
+- Prior to accessing the geolocation state, ensure to verify the isSupported flag.
+
+
+### Types
+
+```typescript static
+import { type UseGeolocationStateResult } from './useGeolocationState';
+import { type UseGeolocationEventsResult } from './useGeolocationEvents';
+/**
+ * Returns an array where the first item is the geolocation state from the `useGeolocationState` hook and the
+ * second one is the object of callback setters from the `useGeolocationEvents` hook.
+ * It is intended as a shortcut to those hooks.
+ */
+declare const useGeolocation: (options?: PositionOptions) => [UseGeolocationStateResult, UseGeolocationEventsResult];
+export default useGeolocation;
+
+```
+
\ No newline at end of file
diff --git a/docs/useGeolocationEvents.md b/docs/useGeolocationEvents.md
index b2a78646..01c1ab28 100644
--- a/docs/useGeolocationEvents.md
+++ b/docs/useGeolocationEvents.md
@@ -1,22 +1,28 @@
# useGeolocationEvents
-Returns an object of handler setters to handle the geolocation-related events. So far, the supported methods are: `onChange`, invoked when
-the position changes and `onError`, invoked when an error occur while retrieving the position.
-The returned object also contains the `isSupported` boolean flag reporting whether the geolocation API is supported.
+A hook that returns an object of callback setters (functions to set the callback that will be performed once an event is fired)
+to handle geolocation-related events. So far, the supported methods are:
-**Please note:** the returned handler setters should invoked immediately in the function component's body, do not try to call this functions
-asynchronously.
+- onChange, invoked when the position changes
+- onError, invoked when an error occurs while retrieving the position.
+
+The returned object also contains the `isSupported boolean flag, reporting whether the geolocation API is supported.
+
+**Please note**: the returned callback setters should be invoked immediately in the function component's body. Do not try to call these
+functions asynchronously.
### Why? π‘
-- takes care of adding the geolocation events listeners
-- takes care of cleaning the listener when the component will unmount
-- allow to perform abstractions on geolocation related events
+- Manages the addition of geolocation event listeners
+- Handles the cleaning of the listeners when the component unmounts
+- Enables the creation of abstractions for geolocation-related events
### Basic Usage:
```jsx harmony
import { useState } from 'react';
+import { Typography } from 'antd';
+
import useGeolocationEvents from 'beautiful-react-hooks/useGeolocationEvents';
const GeoReporter = () => {
@@ -29,12 +35,12 @@ const GeoReporter = () => {
onError((err) => setError(err));
return (
-
- Geolocation supported: {isSupported ? 'yes' : 'no'}
- {!error && position && (
- lat: {position.coords.latitude}, lng: {position.coords.longitude}
- )}
-
+
+ Geolocation supported: {isSupported ? 'yes' : 'no'}
+ {!error && position && (
+ lat: {position.coords.latitude}, lng: {position.coords.longitude}
+ )}
+
);
};
@@ -45,9 +51,31 @@ const GeoReporter = () => {
#### β
When to use
-- If in need to abstract some geolocation related logic into a custom hooks
+- Use this hook when you need to abstract geolocation-related logic into a custom hook
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code.
+- Do not use the returned callback setter asynchronously. Doing so will have no effect and may cause bugs in your code. Instead, be sure to
+ invoke the callback setters immediately in the function component's body
+
+
+### Types
+
+```typescript static
+import { type BRHGeolocationPosition, type BRHGeolocationPositionError } from './shared/types';
+export interface UseGeolocationEventsResult {
+ isSupported: boolean;
+ onChange: (callback: (position: BRHGeolocationPosition) => void) => void;
+ onError: (callback: (error: BRHGeolocationPositionError) => void) => void;
+}
+/**
+ * Returns a frozen object of callback setters to handle the geolocation events.
+ * So far, the supported methods are: `onChange`, invoked when the position changes and `onError`, invoked when
+ * an error occur while retrieving the position.
+ * The returned object also contains the `isSupported` boolean flag reporting whether the geolocation API is supported.
+ */
+declare const useGeolocationEvents: (options?: PositionOptions) => Readonly;
+export default useGeolocationEvents;
+
+```
+
\ No newline at end of file
diff --git a/docs/useGeolocationState.md b/docs/useGeolocationState.md
index cb112fce..05ae05da 100644
--- a/docs/useGeolocationState.md
+++ b/docs/useGeolocationState.md
@@ -1,23 +1,28 @@
# useGeolocationState
-Returns an object containing the `position` information, the `isSupported` boolean flag reporting whether the geolocation API is supported
-or not, the `isRetrieving` boolean flag reporting whether the hook is fetching the current position or not ans the `onError`, invoked when an error occur while retrieving the position.
+A hook that returns an object comprising information on the response from
+the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API). \
+This object properties are:
-The position is retrieved by using the
-[Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API), when supported.
+- the `position` information, which is the actual response from the geolocation API
+- the `isSupported` boolean flag, indicating whether the geolocation API is supported or not
+- the `isRetrieving` boolean flag, indicating whether the hook is currently retrieving the position or not
+- the `onError` function, invoked when an error occurs while retrieving the position
-It possibly accepts an object of [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions)
-to be used as parameter when using the `Geolocation.getCurrentPosition()` method.
+It also accepts a [geolocation options object](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) to be utilized as a
+parameter while utilizing the `Geolocation.getCurrentPosition()` method.
### Why? π‘
-- allow to easily access the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API)
-- takes care of cleaning the listener when the component will unmount
-- allow to perform abstractions on geolocation related events
+- facilitates streamlined access to
+ the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API), which allows for
+ geolocation tracking and position updates
+- enables the abstraction of geolocation-related events, allowing for more flexible and scalable code implementation
### Basic Usage:
```jsx harmony
+import { Typography } from 'antd';
import useGeolocationState from 'beautiful-react-hooks/useGeolocationState';
const PositionReporter = () => {
@@ -28,14 +33,14 @@ const PositionReporter = () => {
});
return (
-
- The current position is:
- {isRetrieving && (Retrieving position...
)}
- {isSupported && position && [
- Lat: {position.coords.latitude}
,
- Lng: {position.coords.longitude}
- ]}
-
+
+ The current position is:
+ {geoState.isRetrieving && (Retrieving position... )}
+ {geoState.isSupported && geoState.position && [
+ Lat: {geoState.position.coords.latitude} ,
+ Lng: {geoState.position.coords.longitude}
+ ]}
+
);
};
@@ -44,7 +49,7 @@ const PositionReporter = () => {
### Options:
-Before using, please read about the [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions)
+Read more on the [geolocation options documentation](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions)
```jsx harmony
import useGeolocationState from 'beautiful-react-hooks/useGeolocationState';
@@ -61,14 +66,14 @@ const PositionReporter = () => {
});
return (
-
- The current high accuracy position is:
- {isRetrieving && (Retrieving position...
)}
- {isSupported && position && [
- Lat: {position.coords.latitude}
,
- Lng: {position.coords.longitude}
- ]}
-
+
+ The current position is:
+ {geoState.isRetrieving && (Retrieving position... )}
+ {geoState.isSupported && geoState.position && [
+ Lat: {geoState.position.coords.latitude} ,
+ Lng: {geoState.position.coords.longitude}
+ ]}
+
);
};
@@ -79,10 +84,39 @@ const PositionReporter = () => {
#### β
When to use
-- If in need to easily access the Geolocation API
-- If in need to abstract some geolocation related logic into a custom hooks
+- Use this hook when you require effortless access to the Geolocation API
#### π What not to do
-- Don't use this hook to try to guess the user's device capabilities
-- Don't access the geolocation state before checking hte `isSupported` flag
+- Do not utilize this hook to speculate the user's device capabilities.
+- Prior to accessing the geolocation state, ensure to verify the isSupported flag.
+
+
+### Types
+
+```typescript static
+import { type BRHGeolocationPosition, type BRHGeolocationPositionError, type SomeCallback } from './shared/types';
+export interface GeolocationState {
+ readonly isSupported: boolean;
+ readonly isRetrieving: boolean;
+ readonly position: BRHGeolocationPosition;
+}
+export interface UseGeolocationStateResult extends GeolocationState {
+ onError: (callback: SomeCallback) => void;
+}
+/**
+ * Returns a frozen object containing the `position` object, the `isSupported` boolean flag, reporting whether the
+ * geolocation API is supported or not and the `isRetrieving` boolean flag reporting whether the hook is fetching the
+ * current position.
+ * The position is retrieved by using the
+ * [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API),
+ * when supported.
+ * It possibly accepts an object of [geolocation options]
+ * (https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) to be used as parameter when using the
+ * `Geolocation.getCurrentPosition()` method.
+ */
+declare const useGeolocationState: (options?: PositionOptions) => Readonly;
+export default useGeolocationState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useGlobalEvent.md b/docs/useGlobalEvent.md
index d8b4c614..18112850 100644
--- a/docs/useGlobalEvent.md
+++ b/docs/useGlobalEvent.md
@@ -1,21 +1,19 @@
# useGlobalEvent
-Accepts an event name to be attached to the window global object, then returns a handler setter for that event.
+A hook that streamlines event handling in your application, ensuring that event listeners are added and removed at the appropriate times,
+without requiring you to manage them manually.\
+Simply provide the name of the event you want to attach to the `window` object, and the hook will take care of the rest.
### Why? π‘
-- takes care of adding a listener for a given event to the window object
-- takes care of removing the listener when the component will unmount
+- Simplifies the process of adding a listener for a specific event to the `window` object.
+- Automates the removal of the listener when the component is unmounted.
### Basic Usage:
-`useGlobalEvent` returns a handler setter for the defined event to be immediately invoked.
-
-**Please note**: the handler setter is only meant to change the callback reference, it does not cause the component rerender unless
-differently specified in the function's body. It's not invoked asynchronously
-
```jsx harmony
import { useState } from 'react';
+import { Typography, Alert, Tag, Space } from 'antd';
import useGlobalEvent from 'beautiful-react-hooks/useGlobalEvent';
const TestComponent = () => {
@@ -27,8 +25,14 @@ const TestComponent = () => {
});
return (
-
- Current window width: {windowWidth}
+
+
+
+
+
+ window width: {windowWidth}
+
+
);
};
@@ -43,6 +47,7 @@ under the hood, it's possible to specify the listener characteristics by passing
```jsx harmony
import { useState } from 'react';
+import { Typography, Alert, Tag, Space } from 'antd';
import useGlobalEvent from 'beautiful-react-hooks/useGlobalEvent';
const TestComponent = () => {
@@ -55,8 +60,14 @@ const TestComponent = () => {
});
return (
-
- Current window width: {windowWidth}
+
+
+
+
+
+ window width: {windowWidth}
+
+
);
};
@@ -68,11 +79,22 @@ const TestComponent = () => {
#### β
When to use
-- When in need of listening to a specific event from the window global object
+- To capture a specific event from the `window` global object.
#### π What not to do
-- When you can archive the same result by using a callback, **please remember listening/firing events directly to/from HTMLElement(s) in
- React is considered an anti-pattern**
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code
+- Avoid using the returned callback setter asynchronously, as it will only change the handler and may cause bugs in your code.
+
+
+### Types
+
+```typescript static
+import { type CallbackSetter } from './shared/types';
+/**
+ * Accepts an event name then returns a callback setter for a function to be performed when the event triggers.
+ */
+declare const useGlobalEvent: (eventName: keyof WindowEventMap, opts?: AddEventListenerOptions) => CallbackSetter;
+export default useGlobalEvent;
+
+```
+
\ No newline at end of file
diff --git a/docs/useInfiniteScroll.md b/docs/useInfiniteScroll.md
index a1b234fc..0b1f209c 100644
--- a/docs/useInfiniteScroll.md
+++ b/docs/useInfiniteScroll.md
@@ -1,12 +1,12 @@
# useInfiniteScroll
-Accepts an HTML Element ref, then returns a function that allows you to handle the infinite scroll for that specific element.
+A hook that accepts an HTML Element reference and returns a function that facilitates handling infinite scroll for that specific element.
### Why? π‘
-- takes care of adding the infinite scroll-related events listeners to the defined target
-- takes care of cleaning the listener when the component will unmount
-- allow to easily implement infinite scroll business logic
+- adds the required event listeners for infinite scrolling to the defined target
+- takes care of cleaning up the event listener when the component is unmounted, reducing the risk of memory leaks in your application
+- simplifies the implementation of infinite scroll business logic by providing an intuitive and easy-to-use interface
### Basic Usage:
@@ -14,6 +14,7 @@ Provide a DOM ref as first parameter to `useInfiniteScroll`
```jsx harmony
import { useState, useRef } from 'react';
+import { Alert, List, Typography } from 'antd';
import useInfiniteScroll from 'beautiful-react-hooks/useInfiniteScroll';
const generateRandomNo = () => Math.floor(Math.random() * 11)
@@ -47,29 +48,33 @@ const TestComponent = () => {
setIsFetching(true)
fetchMock()
- .then((next) => setData([...data, ...next]))
- .finally(() => setIsFetching(false))
+ .then((next) => setData([...data, ...next]))
+ .finally(() => setIsFetching(false))
}
})
return (
-
-
-
-
Scroll to "load" more contents…
-
- {data.map((item) => (
- mock item no: {item}
- ))}
-
- {isFetching && (
-
- Loading next data...
+
+
+
+
+
(
+
+ mock item no: {item}
+
+ )}
+ />
+ {isFetching && (
+
+ Loading next data...
+
+ )}
+
- )}
-
-
-
+
);
};
@@ -80,9 +85,25 @@ const TestComponent = () => {
#### β
When to use
-- When in need of abstracting your own infinite scroll business logic
+- Use this hook to abstract your own infinite scroll business logic and streamline the implementation of this functionality in your
+ application
#### π What not to do
-- Don't rely on this hook to debounce/throttling your functions, if you're implementing a pagination-like infinite scroll you should
- debounce/throttle your own functions
+- Avoid using this hook to debounce or throttle your functions. If you're implementing a pagination-like infinite scroll, it's best to
+ handle this debounce/throttle functionality yourself, to ensure that your application behaves exactly as you intend.
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Accepts an HTML Element ref, then returns a function that allows you to handle the infinite
+ * scroll for that specific element.
+ */
+declare const useInfiniteScroll:
(ref: RefObject, delay?: number) => import("./shared/types").CallbackSetter;
+export default useInfiniteScroll;
+
+```
+
\ No newline at end of file
diff --git a/docs/useInterval.md b/docs/useInterval.md
index 822bf3ea..b8323ef3 100644
--- a/docs/useInterval.md
+++ b/docs/useInterval.md
@@ -1,19 +1,22 @@
# useInterval
-An async-utility hook that accepts a callback `function` and a `delay time` (*in milliseconds*), then repeat the execution of the given
-function by the defined time.
+A hook that facilitates the utilization of the `setInterval` function in React function components. This hook receives a callback function
+and a delay duration as inputs, and subsequently, executes the given function at regular intervals with the specified delay time between
+each invocation
### Why? π‘
-- takes care of performing the given callback regardless the component re-renders;
-- cancels the interval when the component unmount (or not, depends by the defined options);
-- returns the interval state (cleared/not cleared)
-- returns a method to possibly cancel the set interval (cause the component re-render)
+- Ensures that the given callback is executed reliably, even when the component re-renders;
+- Automatically cancels the interval when the component unmounts (although this behavior can be modified by adjusting the options);
+- Provides information about the current state of the interval (whether it has been cleared or not);
+- Offers a method to cancel the set interval, which can trigger a re-render of the component if desired.
### Basic Usage:
```jsx harmony
import { useState } from 'react';
+import { Tag, Typography } from 'antd';
+
import useInterval from 'beautiful-react-hooks/useInterval';
const DelayedContentComponent = () => {
@@ -25,8 +28,8 @@ const DelayedContentComponent = () => {
}, 1000);
return (
-
- Rendering since {seconds} seconds
+
+ Rendering since {seconds} seconds
);
};
@@ -36,12 +39,14 @@ const DelayedContentComponent = () => {
### State & clear method:
-The hook returns the state of the timeout (a boolean, cleared/not cleared) and a method to possibly clear it.
+The hook returns information about the timeout's state (whether it has been cleared or not, represented by a boolean flag), and also offers
+a method to potentially clear it.
-**Note:** programmatically clearing the timeout will cause the component re-render.
+**Note**: Invoking this method to programmatically clear the timeout may trigger the component re-rendering.
```jsx harmony
import { useState } from 'react';
+import { Tag, Typography, Button } from 'antd';
import useInterval from 'beautiful-react-hooks/useInterval';
const DelayedContentComponent = () => {
@@ -52,9 +57,9 @@ const DelayedContentComponent = () => {
return (
- Rendering since {seconds} seconds
- {!isCleared && Stop it! }
- {isCleared && Interval cleared!
}
+ Rendering since {seconds} seconds
+ {!isCleared && Stop the counter }
+ {isCleared && Interval cleared! }
);
};
@@ -64,7 +69,7 @@ const DelayedContentComponent = () => {
### Options:
-`useInterval` might accept a options object provided as eventual parameter.
+It is possible to provide an options object as the last parameter of the hook.
#### cancelOnUnmount:
@@ -74,6 +79,7 @@ Defines whether the timeout should be cleared on unmount.
```jsx harmony
import { useState } from 'react';
+import { Tag, Typography, Button } from 'antd';
import useInterval from 'beautiful-react-hooks/useInterval';
const DelayedContentComponent = () => {
@@ -84,7 +90,8 @@ const DelayedContentComponent = () => {
return (
- Content rendering since {seconds} but will not be cleared on unmount
+ Rendering since {seconds} seconds
+ It won't be cleared at unmount
);
};
@@ -96,8 +103,27 @@ const DelayedContentComponent = () => {
#### β
When to use
-- If in need to perform a function every x number of milliseconds regardless the component re-renders
+- When you need to perform a function on a regular interval (e.g., every x number of milliseconds), regardless of whether the component
+ re-renders.
#### π When not to use
-- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+- When attempting to use it asynchronously, since doing so would violate the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+
+
+### Types
+
+```typescript static
+import { type GenericFunction } from './shared/types';
+export interface UseIntervalOptions {
+ cancelOnUnmount?: boolean;
+}
+/**
+ * An async-utility hook that accepts a callback function and a delay time (in milliseconds), then repeats the
+ * execution of the given function by the defined milliseconds.
+ */
+declare const useInterval: (fn: TCallback, milliseconds: number, options?: UseIntervalOptions) => [boolean, () => void];
+export default useInterval;
+
+```
+
\ No newline at end of file
diff --git a/docs/useIsFirstRender.md b/docs/useIsFirstRender.md
index 444f7c6d..6405f1a5 100644
--- a/docs/useIsFirstRender.md
+++ b/docs/useIsFirstRender.md
@@ -1,17 +1,20 @@
# useIsFirstRender
--- This hook return a boolean set to true at the mount time and then always false --
+A hook that returns a boolean value indicating whether it's the first render or not.
+
+This hook can be used to conditionally execute logic or render components based on whether it's the first time the component is being
+rendered or if it's being re-rendered due to a state or prop change.
### π‘ Why?
-- Give information about if it's first render
+- A useful tool for managing component rendering behavior and enables you to write more efficient and flexible code
### Basic Usage:
```jsx harmony
import { useState, useCallback } from 'react';
-import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
-import useIsFirstRender from 'beautiful-react-hooks/useIsFirstRender';
+import { Button, Typography } from 'antd';
+import useIsFirstRender from 'beautiful-react-hooks/useIsFirstRender';
const UseIsFirstRenderExample = () => {
const [data, setData] = useState(0)
@@ -20,13 +23,12 @@ const UseIsFirstRenderExample = () => {
const setNewDate = useCallback(() => setData(Date.now()), []);
return (
-
- Click on the button to update isFirstRender flag
- isFirstRender: {isFirstRender ? 'yes' : 'no'}
-
-
+
+ Click on the button to update isFirstRender flag
+ isFirstRender: {isFirstRender ? 'yes' : 'no'}
+
Update data
-
+
);
};
@@ -34,8 +36,12 @@ const UseIsFirstRenderExample = () => {
```
-### Mastering the hooks
+
+### Types
+
+```typescript static
+declare const useIsFirstRender: () => boolean;
+export default useIsFirstRender;
-#### β
When to use
-
-- When you need to get information if first render occurs
+```
+
\ No newline at end of file
diff --git a/docs/useLifecycle.md b/docs/useLifecycle.md
index e0454056..34ee43e7 100644
--- a/docs/useLifecycle.md
+++ b/docs/useLifecycle.md
@@ -1,18 +1,23 @@
# useLifecycle
-Accepts two functions to be performed during the component's lifecycle.
+A hook that facilitates performing specific functions during the lifecycle of a component.
-The first one will be fired after **component did mount**, the second right before the **component unmounts**.
+It accepts two functions as arguments. The first function will be executed after the component has mounted, which means that the component
+has been initialized and rendered on the screen. The second function will be executed right before the component unmounts, which happens
+when the component is removed from the screen or destroyed.
+
+Using this hook allows for greater control and customization of a component's behavior.
### Why? π‘
-- Encloses the "lifecycle hooks" such as `useDidMount` and `useWillUnmount`;
-- It's as a shortcut to `useEffect(onMount, [])` and `useEffect(() => () => willUnmount, [])`;
+- Provides a wrapper for "lifecycle hooks" including `useDidMount` and `useWillUnmount`.
+- Serves as a shorthand for `useEffect(onMount, [])` and `useEffect(() => () => willUnmount, [])`.
### Basic Usage:
```jsx harmony
import { useCallback } from 'react';
+import { Alert } from 'antd';
import useLifecycle from 'beautiful-react-hooks/useLifecycle';
/**
@@ -30,8 +35,8 @@ const LifeCycleComponent = () => {
useLifecycle(onMount, onUnmount);
return (
-
- Check the javascript console
+
+
);
};
@@ -41,13 +46,15 @@ const LifeCycleComponent = () => {
### Callback setter syntax:
-if no parameters are provided, the returned object of handler setters can be used to set the `useDidMount` and `useWillUnmount` handlers, as
-long as they are immediately invoked.
+If you don't provide any parameters, you can use the returned callback setters to set the `useDidMount` and `useWillUnmount` handlers.
+However, you must immediately invoke them to make it work.
-**Please note**: the returned handler setters are meant to change the value of the callback reference only, they do not cause the component
-rerender nor should not be invoked asynchronously.
+**Note**: It's important to keep in mind that the callback setters are intended to modify the value of the callback reference only. They do
+not cause the component to rerender, and you should not invoke them asynchronously. This ensures that the behavior of your code remains
+predictable and that your project runs smoothly.
```jsx harmony
+import { Alert } from 'antd';
import useLifecycle from 'beautiful-react-hooks/useLifecycle';
const ComponentDidMount = () => {
@@ -62,8 +69,8 @@ const ComponentDidMount = () => {
});
return (
-
- Check the javascript console
+
+
);
};
@@ -75,9 +82,6 @@ const ComponentDidMount = () => {
When using a React function component you should not really think of it in terms of "lifecycle".
-The `useLifecycle` hook is indeed intended as a shortcut to `useEffect(onMount, [])` and
-`useEffect(() => () => willUnmount, [])`.
-
To deep understanding `useEffect`, what it is and how it should be properly used, please read
"[A complete guide to useEffect](https://overreacted.io/a-complete-guide-to-useeffect/)"
by [Dan Abramov](https://twitter.com/dan_abramov)
@@ -86,11 +90,29 @@ by [Dan Abramov](https://twitter.com/dan_abramov)
#### β
When to use
-- When in need of performing a function after the component did mount
-- When in need of performing a function right before the component unmounts
-- When in need of a shortcut to the component lifecycle
+- When you need to execute a function after the component has mounted
+- When you need to execute a function immediately before the component unmounts
+- When you require a shortcut to the component lifecycle
#### π When not to use
-- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
-- If using the handler setters, they should not be used asynchronously but immediately invoked.
+- If you need to use it asynchronously, as this violates the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+- If you're using the callback setters, you must not use them asynchronously, but instead, immediately invoke them.
+
+
+### Types
+
+```typescript static
+import { type GenericFunction } from './shared/types';
+/**
+ * Returns an object wrapping lifecycle hooks such as `useDidMount` or `useWillUnmount`.
+ * It is intended as a shortcut to those hooks.
+ */
+declare const useLifecycle: (mount?: TMount | undefined, unmount?: TUnmount | undefined) => {
+ onDidMount: import("./shared/types").CallbackSetter;
+ onWillUnmount: import("./shared/types").CallbackSetter;
+};
+export default useLifecycle;
+
+```
+
\ No newline at end of file
diff --git a/docs/useLocalStorage.md b/docs/useLocalStorage.md
index 313543c2..18c5aa84 100644
--- a/docs/useLocalStorage.md
+++ b/docs/useLocalStorage.md
@@ -1,16 +1,17 @@
# useLocalStorage
-A hook for storing values into [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
+A hook that enables effortless storage and retrieval of values in the
+browser's [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
### π‘ Why?
-- A quick way to use the `localStorage` in your React components.
+- A fast and efficient method to implement the `localStorage` functionality in your React components
### Basic Usage:
```jsx harmony
import React, { useCallback } from 'react';
-import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
+import { Button, Tag, Typography } from 'antd';
import useLocalStorage from 'beautiful-react-hooks/useLocalStorage';
const NotificationBadgeExample = ({ notifications }) => {
@@ -20,13 +21,17 @@ const NotificationBadgeExample = ({ notifications }) => {
setNotificationCount(0);
}, [notificationCount]);
+ const Actions = [
+
+ You've got {notificationCount} new messages
+
+ ]
+
return (
-
- Click on the badge to clear from the local storage
-
-
- You've got {notificationCount} new messages
-
+
+
+ Click on the following button to clear data from the demo-notification-count local storage key.
+
)
};
@@ -34,6 +39,14 @@ const NotificationBadgeExample = ({ notifications }) => {
```
+### Interface
+
+```typescript
+type SetValue = (value: TValue | ((previousValue: TValue) => TValue)) => void
+
+declare const useLocalStorage: (storageKey: string, defaultValue?: any) => [TValue, SetValue]
+```
+
### Mastering the hooks
#### β
When to use
@@ -43,3 +56,16 @@ const NotificationBadgeExample = ({ notifications }) => {
#### π When not to use
- Do not use this hook as a state manager, the `localStorage` is meant to be used for small pieces of data
+
+
+### Types
+
+```typescript static
+/**
+ * Save a value on local storage
+ */
+declare const useLocalStorage: (storageKey: string, defaultValue?: any) => [TValue | null, (value: TValue | ((previousValue: TValue) => TValue)) => void];
+export default useLocalStorage;
+
+```
+
\ No newline at end of file
diff --git a/docs/useMediaQuery.md b/docs/useMediaQuery.md
index 93b698a9..98a84e2c 100644
--- a/docs/useMediaQuery.md
+++ b/docs/useMediaQuery.md
@@ -1,18 +1,14 @@
# useMediaQuery
-Accepts a media query string then uses the [matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia)
-API to determine if it matches with the current document.
+A hook that takes in a media query string and utilizes the [matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia)
+API to check whether it corresponds to the present document.
-It also monitor the document changes to detect when it stops matching the given media query.
+Additionally, it tracks changes in the document to detect when it no longer corresponds to the provided media query.
-Returns the validity state of the given media query.
-
-### Why? π‘
-
-- takes care of re-rendering the component when the given media query changes
-- get rid of the listener when the component will unmount
+The hook returns the validity status of the media query provided.
```jsx harmony
+import { Tag, Typography, Space, Alert } from 'antd';
import useMediaQuery from 'beautiful-react-hooks/useMediaQuery';
const MediaQueryReporter = () => {
@@ -20,9 +16,12 @@ const MediaQueryReporter = () => {
const isLarge = useMediaQuery('(min-width: 48rem)');
return (
-
- Small view? {isSmall ? 'yes' : 'no'}
- Large view? {isLarge ? 'yes' : 'no'}
+
+
+
+ Small view? {isSmall ? 'yes' : 'no'}
+ Large view? {isLarge ? 'yes' : 'no'}
+
);
};
@@ -34,9 +33,27 @@ const MediaQueryReporter = () => {
#### β
When to use
-- When a component should have a different layout/behaviour on different medias
-- Mount/Unmount sub-components according to a defined media-query
+- If a component needs to display a different layout or behavior on various media types
+- Conditionally render sub-components based on a specified media query
#### π When not to use
-- Do not use this hook to define the user device
+- Avoid using this hook to identify the user's device, use agent detection instead
+
+
+### Types
+
+```typescript static
+/**
+ * Accepts a media query string then uses the
+ * [window.matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) API to determine if it
+ * matches with the current document.
+ * It also monitor the document changes to detect when it matches or stops matching the media query.
+ * Returns the validity state of the given media query.
+ *
+ */
+declare const useMediaQuery: (mediaQuery: string) => boolean;
+export default useMediaQuery;
+
+```
+
\ No newline at end of file
diff --git a/docs/useMouse.md b/docs/useMouse.md
index 06df4ab2..bde9df76 100644
--- a/docs/useMouse.md
+++ b/docs/useMouse.md
@@ -1,23 +1,24 @@
-# useMouse
+# `useMouse`
-Returns an array where the first item is the mouse state from [useMouseState](./useMouseState.md) and the second item is an wrapper of all
-the handler-setters from [useMouseEvents](./useMouseEvents.md).
+A hook that combines the functionalities of [useMouseState](./useMouseState.md) and [useMouseEvents](./useMouseEvents.md), returning an
+array where the first item is the mouse state and the second item is a wrapper of all the handler-setters.
-`useMouse` is in fact intended as a shortcut to those hooks.
+`useMouse` is intended as a shortcut to avoid the need for using both `useMouse`State and `useMouse`Events separately.
### Why? π‘
-- allow to easily receive the mouse position
-- takes care of adding the mouse events listeners globally or to the defined target
-- takes care of cleaning the listener when the component will unmount
-- allows performing abstractions on mouse related events
+- Provides an easy way to obtain the mouse position
+- Automatically adds mouse event listeners either globally or to the specified target element
+- Automatically removes the listeners when the component unmounts
+- Enables abstractions on mouse-related events
### Basic Usage:
-Provide a DOM ref as first parameter to `useMouse`
+Provide a DOM ref as first parameter to ``useMouse``
```jsx harmony
import { useRef, useState } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useMouse from 'beautiful-react-hooks/useMouse';
const MouseReporter = () => {
@@ -29,14 +30,15 @@ const MouseReporter = () => {
onMouseLeave(() => setShowCoords(false));
return (
-
-
- Move the mouse over this text to get its current coordinates:
- {showCoords && (
-
{position.clientX}, {position.clientY}
- )}
-
-
+
+
+
+
+ ClientX: {position.clientX}
+ ClientY: {position.clientY}
+
+
+
);
};
@@ -49,6 +51,7 @@ If no ref is provided to `useMouse` it will use the window global object assign
```jsx harmony
import { useState } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useMouse from 'beautiful-react-hooks/useMouse';
const MouseReporter = () => {
@@ -59,16 +62,13 @@ const MouseReporter = () => {
onMouseUp(() => setMouseDown(false));
return (
-
-
- The current mouse global coordinates are: {position.clientX}, {position.clientY}
- {mouseDown && (
-
- Holding click
-
- )}
-
-
+
+
+
+ ClientX: {position.clientX}
+ ClientY: {position.clientY}
+
+
);
};
@@ -79,25 +79,52 @@ const MouseReporter = () => {
#### β
When to use
-- If in need to get the mouse current position
-- If in need to abstract some mouse related logic into a custom hooks
+- use `useMouse` to obtain the current mouse position.
+- use `useMouse` to abstract custom mouse-related logic into a hook.
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code.
-- Absolutely avoid using `useMouse` handler setters to replace the standard mouse handler props.
-- `useMouse` is meant to be used to abstract more complex hooks that need to control the mouse, for example: a drag n drop hook.
-- Using `useMouse` handlers instead of the classic props approach it's just as bad as it sounds since you'll lose the React SyntheticEvent
- performance boost.
-- If you were doing something like the following, please keep doing it:
+- Do not use the returned callback setters asynchronously, as doing so will have no effect and may result in bugs in your code.
+- Avoid using `useMouse` callback setters to replace standard mouse handler props.
+- `useMouse` is designed to be used for abstracting more complex hooks that need to control the mouse, such as a drag-and-drop hook.
+- Using `useMouse` handlers instead of the classic props approach will result in decreased performance due to the loss of the React
+ SyntheticEvent performance boost. If you were using a classic props approach before, continue to do so.
```jsx harmony static noedit
const MyComponent = (props) => {
const { mouseDownHandler } = props;
return (
-
+
);
};
-```
+```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Returns an array where the first item is the mouse state from the `useMouseState` hook and the second item
+ * is the object of callback setters from the `useMouseEvents` hook.
+ * It is intended as a shortcut to those hooks.
+ */
+declare const useMouse: (targetRef?: RefObject | undefined) => ({
+ clientX: number;
+ clientY: number;
+ screenX: number;
+ screenY: number;
+} | Readonly<{
+ onMouseDown: import("./shared/types").CallbackSetter;
+ onMouseEnter: import("./shared/types").CallbackSetter;
+ onMouseLeave: import("./shared/types").CallbackSetter;
+ onMouseMove: import("./shared/types").CallbackSetter;
+ onMouseOut: import("./shared/types").CallbackSetter;
+ onMouseOver: import("./shared/types").CallbackSetter;
+ onMouseUp: import("./shared/types").CallbackSetter;
+}>)[];
+export default useMouse;
+
+```
+
\ No newline at end of file
diff --git a/docs/useMouseEvents.md b/docs/useMouseEvents.md
index 3722bdb3..202ecd02 100644
--- a/docs/useMouseEvents.md
+++ b/docs/useMouseEvents.md
@@ -1,19 +1,19 @@
-# useMouseEvents
+# useMouseEvents
-Returns a set of handler setters to control mouse events.
-It possibly accepts a DOM ref to target the event(s) to.
-If the target is not provided the events will be globally attached to the `document` object.
+A hook that provides an easy way to manage mouse events by returning a set of callback setters. The returned setters allow control over
+various mouse events including `onMouseDown`, `onMouseEnter`, `onMouseLeave`, `onMouseMove`, `onMouseOut`, `onMouseOver`, and `onMouseUp`.
-Available handler setters: `onMouseDown`, `onMouseEnter`, `onMouseLeave`, `onMouseMove`, `onMouseOut`, `onMouseOver`, `onMouseUp`;
+The hook optionally accepts a reference to a DOM element to target the desired event(s) to. If no target is provided, the events will be
+attached globally to the document object.
-**Please note:** the returned handler setters should be immediately invoked in the component's body, do not try to call this functions
-asynchronously.
+It is important to note that the returned callback setters should be immediately invoked within the component's body, and should not be
+called asynchronously.
### Why? π‘
-- takes care of adding the mouse events listeners globally or to a defined target
-- takes care of cleaning the listener when the component unmounts
-- allows performing abstractions on mouse related events
+- handles the addition of mouse event listeners either globally or to a specified target.
+- takes care of cleaning up the listeners when the component is unmounted.
+- enables the implementation of abstractions on mouse-related events.
### Basic Usage:
@@ -21,10 +21,11 @@ Provide a DOM ref as first parameter to `useMouseEvents`
```jsx harmony
import { useRef, useState } from 'react';
-import useMouseEvents from 'beautiful-react-hooks/useMouseEvents';
+import { Tag, Space, Alert } from 'antd';
+import useMouseEvents from 'beautiful-react-hooks/useMouseEvents';
const MyComponent = () => {
- const [coordinates, setCoordinates] = useState();
+ const [coordinates, setCoordinates] = useState([0, 0]);
const ref = useRef();
const { onMouseMove, onMouseLeave } = useMouseEvents(ref);
@@ -34,16 +35,19 @@ const MyComponent = () => {
});
onMouseLeave(() => {
- setCoordinates(undefined);
+ setCoordinates([0, 0]);
});
return (
-
-
- Move mouse over me to get its current coordinates.
- {coordinates &&
Coordinates x:{coordinates[0]} y:{coordinates[1]}
}
-
-
+
+
+
+
+ ClientX: {coordinates[0]}
+ ClientY: {coordinates[1]}
+
+
+
);
};
@@ -52,11 +56,12 @@ const MyComponent = () => {
### Global events
-Avoid providing any argument to `useMouseEvents` to attach the events globally
+If no ref is provided to `useMouseEvents` it will use the window global object assign the events to
```jsx harmony
import { useState } from 'react';
-import useMouseEvents from 'beautiful-react-hooks/useMouseEvents';
+import { Tag, Space, Alert } from 'antd';
+import useMouseEvents from 'beautiful-react-hooks/useMouseEvents';
const MyComponent = () => {
const [coordinates, setCoordinates] = useState([0, 0]);
@@ -68,10 +73,13 @@ const MyComponent = () => {
});
return (
-
- The current mouse coordinates are:
- x:{coordinates[0]} y:{coordinates[1]}
-
+
+
+
+ ClientX: {coordinates[0]}
+ ClientY: {coordinates[1]}
+
+
);
};
@@ -82,24 +90,55 @@ const MyComponent = () => {
#### β
When to use
-- When need to abstract touch related logics into custom hooks(s)
+- When you need to abstract mouse-related logics into custom hooks(s)
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler
- possibly leading to bugs in your code.
-- Absolutely avoid using `useMouseEvents` handler setters to replace the standard mouse handler props.
-- `useMouseEvents` is meant to be used to abstract more complex hooks that need to control the mouse, for example: a drag n drop hook.
-- Using `useMouseEvents` handlers instead of the classic props approach it's just as bad as it sounds since you'll
-lose the React SyntheticEvent performance boost.
-- If you were doing something like the following, please keep doing it:
+- Do not use the returned callback setters asynchronously, as doing so will have no effect and may result in bugs in your code.
+- Avoid using `useMouseEvents` callback setters to replace standard mouse handler props.
+- `useMouseEvents` is designed to be used for abstracting more complex hooks that need to control the mouse, such as a drag-and-drop hook.
+- Using `useMouseEvents` handlers instead of the classic props approach will result in decreased performance due to the loss of the React
+ SyntheticEvent performance boost. If you were using a classic props approach before, continue to do so.
```jsx harmony static noedit
const MyComponent = (props) => {
const { mouseDownHandler } = props;
-
+
return (
-
+
);
};
-```
+```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Returns a frozen object of callback setters to handle the mouse events.
+ * It accepts a DOM ref representing the events target.
+ * If a target is not provided the events will be globally attached to the document object.
+ *
+ * ### Shall the `useMouseEvents` callbacks replace the standard mouse handler props?
+ *
+ * **They shall not!**
+ * **useMouseEvents is meant to be used to abstract more complex hooks that need to control mouse**, for instance:
+ * a drag n drop hook.
+ * Using useMouseEvents handlers instead of the classic props approach it's just as bad as it sounds since you'll
+ * lose the React SyntheticEvent performance boost.
+ * If you were doing something like the following:
+ */
+declare const useMouseEvents: (targetRef?: RefObject | undefined, passive?: boolean) => Readonly<{
+ onMouseDown: import("./shared/types").CallbackSetter;
+ onMouseEnter: import("./shared/types").CallbackSetter;
+ onMouseLeave: import("./shared/types").CallbackSetter;
+ onMouseMove: import("./shared/types").CallbackSetter;
+ onMouseOut: import("./shared/types").CallbackSetter;
+ onMouseOver: import("./shared/types").CallbackSetter;
+ onMouseUp: import("./shared/types").CallbackSetter;
+}>;
+export default useMouseEvents;
+
+```
+
\ No newline at end of file
diff --git a/docs/useMouseState.md b/docs/useMouseState.md
index 776777fa..e2eabb07 100644
--- a/docs/useMouseState.md
+++ b/docs/useMouseState.md
@@ -1,15 +1,14 @@
# useMouseState
-Returns a summary of the mouse current position properties (such as clientX, clientY). It accepts a DOM ref representing the events target (
-where attach the events to).
-
-If a target is not provided the events will be globally attached to the `document` object.
+A hook that returns relevant properties from the current mouse position, such as clientX and clientY. To ensure that events are attached to
+the intended target, please provide a DOM reference to the hook. If no target is specified, the events will be attached to the
+the `document` object globally.
### Why? π‘
-- allow to easily inspect the mouse position
-- takes care of adding the mouse events listeners globally or to a defined target
-- takes care of cleaning the listener when the component unmounts
+- Allows to quickly get the mouse position
+- Manages the addition of mouse event listeners either globally or to a defined target
+- Ensures the listener is cleaned up when the component unmounts
### Basic Usage:
@@ -17,6 +16,7 @@ Provide a DOM ref as first parameter to `useMouseState`
```jsx harmony
import { useRef } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useMouseState from 'beautiful-react-hooks/useMouseState';
const MouseReporter = () => {
@@ -24,10 +24,13 @@ const MouseReporter = () => {
const { clientX, clientY } = useMouseState(ref);
return (
-
+
- Move mouse over me to get its current coordinates:
- {clientX}, {clientY}
+
+
+ ClientX: {clientX}
+ ClientY: {clientY}
+
);
@@ -38,18 +41,22 @@ const MouseReporter = () => {
### Global events
-Avoid providing any argument to `useMouseState`
+Attach the mouse events globally by simply not providing any dom reference to the `useMouseState` hook
```jsx harmony
+import { Tag, Space, Alert } from 'antd';
import useMouseState from 'beautiful-react-hooks/useMouseState';
const MouseReporter = () => {
const { clientX, clientY } = useMouseState();
return (
-
- The current mouse coordinates are:
- {clientX}, {clientY}
+
+
+
+ ClientX: {clientX}
+ ClientY: {clientY}
+
);
};
@@ -61,24 +68,26 @@ const MouseReporter = () => {
#### β
When to use
-- When need to abstract touch related logics into custom hooks(s)
-
-#### π What not to do
-
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code.
-- Absolutely avoid using `useMouseEvents` handler setters to replace the standard mouse handler props.
-- `useMouseEvents` is meant to be used to abstract more complex hooks that need to control the mouse, for example: a drag n drop hook.
-- Using `useMouseEvents` handlers instead of the classic props approach it's just as bad as it sounds since you'll lose the React
- SyntheticEvent performance boost.
-- If you were doing something like the following, please keep doing it:
-
-```jsx harmony static noedit
-const MyComponent = (props) => {
- const { mouseDownHandler } = props;
-
- return (
-
- );
+- When you need to abstract mouse-related logics into custom hooks(s)
+- When you need to quickly get the current mouse position
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Returns the current state (position) of the mouse pointer.
+ * It possibly accepts a DOM ref representing the mouse target.
+ * If a target is not provided the state will be caught globally.
+ */
+declare const useMouseState: (targetRef?: RefObject | undefined) => {
+ clientX: number;
+ clientY: number;
+ screenX: number;
+ screenY: number;
};
-```
+export default useMouseState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useMutationObserver.md b/docs/useMutationObserver.md
index 9000ad79..b623d713 100644
--- a/docs/useMutationObserver.md
+++ b/docs/useMutationObserver.md
@@ -1,17 +1,23 @@
# useMutationObserver
-Uses the [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) API to watch for changes being made to the DOM tree
+A hook that employs the [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) API to monitor changes made to
+the Document Object Model (DOM) tree.
+
+This hook enables asynchronous observation of changes to a specified HTML Element. It automatically handles the clean-up of the observation
+process when the associated component is unmounted.
### Why? π‘
-- Asynchronously observes changes of the given HTML Element.
-- Takes care of cleaning the observable once the component is dismount.
+- allows for real-time monitoring of changes to the DOM, without requiring constant polling or manual inspection of the element.
+- provides more granular control over the types of changes being observed, allowing developers to selectively listen for specific events
+ such as attribute modifications, node insertions or removals, and so on.
### Basic Usage:
```jsx harmony
-import { useRef, useState } from 'react';
-import useMutationObserver from 'beautiful-react-hooks/useMutationObserver';
+import { useRef, useState } from 'react';
+import { Tag, Typography } from 'antd';
+import useMutationObserver from 'beautiful-react-hooks/useMutationObserver';
const UseMutationObserverExample = () => {
const ref = useRef();
@@ -23,29 +29,39 @@ const UseMutationObserverExample = () => {
useMutationObserver(ref, incrementMutationCount);
- return (
-
-
+ return (
+
+
-
-
Mutation count: {mutationCount}
-
+ Mutations: {mutationCount}
- );
+ );
};
```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+declare const useMutationObserver:
(ref: RefObject, callback: MutationCallback, options?: MutationObserverInit) => void;
+export default useMutationObserver;
+
+```
+
\ No newline at end of file
diff --git a/docs/useObjectState.md b/docs/useObjectState.md
index fa031632..0a5b97c7 100644
--- a/docs/useObjectState.md
+++ b/docs/useObjectState.md
@@ -1,16 +1,20 @@
# useObjectState
-React state hook that creates setState method which works similar to how useState works, merges object changes into the current state.
+A hook has been developed to emulate the behavior of the now deprecated class Component.setState method. This hook aims to facilitate the
+migration process of legacy class components to the new function components paradigm.
### Why? π‘
-- takes care of automatically destruct the previous state and override this with a new one,
+- Automates the process of destructing the previous state and replacing it with a new one, alleviating the burden of manually handling these
+ operations in function components
+- Allow developers to seamlessly transition their codebase from class components to function components without needing to restructure the
+ existing codebase
### Basic Usage:
```jsx harmony
import { useState, useRef } from 'react';
-import { Button } from 'beautiful-react-ui';
+import { Button, Typography } from 'antd';
import useObjectState from 'beautiful-react-hooks/useObjectState';
const UseObjectStateComponent = () => {
@@ -22,19 +26,22 @@ const UseObjectStateComponent = () => {
const decrement = () => setState({ count: state.count - 1 })
+ const Actions = [
+
+ Increment counter
+ ,
+
+ Decrement counter
+ ,
+
+ Reset counter
+
+ ]
+
return (
-
- State:
- {JSON.stringify(state, null, 2)}
-
- Increment counter
-
-
- Decrement counter
-
-
- Reset counter
-
+
+ State:
+ {JSON.stringify(state, null, '\t')}
);
};
@@ -46,4 +53,18 @@ const UseObjectStateComponent = () => {
#### β
When to use
-- When in need of manage the state which is an object,
+- When required to migrate legacy class components to the new function components paradigm
+
+#### π What not to do
+
+- Don't use this hook in place of `useReducer`.
+
+
+### Types
+
+```typescript static
+declare const useObjectState: (initialState: TState) => [TState, (state: Partial) => void];
+export default useObjectState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useObservable.md b/docs/useObservable.md
index 4b8747f1..5e2b1363 100644
--- a/docs/useObservable.md
+++ b/docs/useObservable.md
@@ -1,18 +1,20 @@
# useObservable
-Make your components reactive with `rxjs`
+A hook that enables reactivity in your components through the utilization of `RxJs` library.
### Why? π‘
-- you can change your data in pipes with default rxjs operators
-- combine data, pipes and create structured code
+- Modify your data using default `RxJs` operators within pipes, providing a cleaner and more concise way of handling asynchronous data
+- Combine data from multiple sources into a single observable stream using various `RxJs` operators, allowing you to create more structured
+ and organized code
### Basic Usage:
-##### Using as [useInterval](./useInterval.md)
+Mimics the behaviour of [useInterval](./useInterval.md) with `RxJs`
```jsx harmony
import { useState } from 'react';
+import { Tag, Typography } from 'antd';
import { interval } from 'rxjs';
import useObservable from 'beautiful-react-hooks/useObservable';
@@ -24,8 +26,8 @@ const ObservableInterval = () => {
useObservable(interval$, setSeconds);
return (
-
- Rendering since {seconds} seconds
+
+ Rendering since {seconds} seconds
);
};
@@ -33,11 +35,12 @@ const ObservableInterval = () => {
```
-##### Using as [useGeolocationState](./useGeolocation.md)
+Mimics the behaviour of [useGeolocationState](./useGeolocation.md) with `RxJs`
```jsx harmony
import { useState } from 'react';
import { Observable } from 'rxjs';
+import { Typography } from 'antd';
import useObservable from 'beautiful-react-hooks/useObservable';
const position$ = new Observable(subscriber => {
@@ -53,15 +56,17 @@ const position$ = new Observable(subscriber => {
const ObservableGeolocation = () => {
const [position, setPosition] = useState({});
+ const { coords } = position;
useObservable(position$, setPosition);
- const { coords } = position;
return (
-
- Current position:
- lat: {coords && coords.latitude}
- long: {coords && coords.longitude}
+
+ Current position:
+ {position.coords && [
+ Lat: {position.coords.latitude} ,
+ Lng: {position.coords.longitude}
+ ]}
);
};
@@ -74,6 +79,7 @@ const ObservableGeolocation = () => {
```jsx harmony
import { useState } from 'react';
import { fromEvent } from 'rxjs';
+import { Typography, Tag } from 'antd';
import useObservable from 'beautiful-react-hooks/useObservable';
const resize$ = fromEvent(window, 'resize');
@@ -85,10 +91,14 @@ const ObservableResize = () => {
const { target } = event;
return (
-
- Resize your window
- Width: {target && target.innerWidth || 0}
- Height: {target && target.innerHeight || 0}
+
+ Resize your window
+
+ width: {target && target.innerWidth || 0}
+
+
+ height: {target && target.innerHeight || 0}
+
);
};
@@ -100,9 +110,23 @@ const ObservableResize = () => {
#### β
When to use
-- If you want to present some data like tables and work with them through the pipes (filter, sort, map etc.)
-- use events wisely
+- when you need to display and manipulate data using reactive programming techniques. `RxJs` pipes can be used for filtering, sorting,
+ mapping, and other transformations.
#### π When not to use
-- When you can do something w/o rx
+- Don't use this hook as a state manager
+
+
+### Types
+
+```typescript static
+import { type Observable, type Observer } from 'rxjs';
+/**
+ * Hook, which helps you combine rxjs flow and setState in your component
+ */
+declare const useObservable: > | ((value: T) => void)>(observable: Observable, setter: F) => void;
+export default useObservable;
+
+```
+
\ No newline at end of file
diff --git a/docs/useOnlineState.md b/docs/useOnlineState.md
index 1fbe80f1..3d6c1966 100644
--- a/docs/useOnlineState.md
+++ b/docs/useOnlineState.md
@@ -1,28 +1,51 @@
# useOnlineState
-Uses the [Navigator online API](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine) to define whether the browser is
-connected or not.
+A hook is available in this library that utilizes
+the [Navigator online API](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine) to determine the connectivity status of
+the user's browser.
-Returns a `boolean` value that if is true indicates the browser is connected.
+This hook returns a boolean value which indicates whether the browser is currently online or offline.
+
+The primary use case for this hook is to facilitate re-rendering of a component when the browser's connectivity status changes. By using
+this hook, your component can respond dynamically to changes in connectivity and update its behavior accordingly
### Why? π‘
-- You want to your component to re-render ether when the connection goes online or offline.
+- Your component requires network connectivity to function correctly and should behave differently when offline
+- You need to trigger some functionality when the user's connectivity status changes, such as syncing data with a server when the user comes
+ back online
### Basic Usage:
```jsx harmony
+import { Tag, Typography } from 'antd';
import useOnlineState from 'beautiful-react-hooks/useOnlineState';
const ConnectionTest = () => {
const isOnline = useOnlineState();
-
+
return (
-
- Connection status: {isOnline ? 'online' : 'offline'}
-
+
+
+ Connection status: {isOnline ? 'online' : 'offline'}
+
+
);
};
```
+
+
+### Types
+
+```typescript static
+/**
+ * Uses the [Navigator online API](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine) to define
+ * whether the browser is connected or not.
+ */
+declare const useOnlineState: () => boolean;
+export default useOnlineState;
+
+```
+
\ No newline at end of file
diff --git a/docs/usePreviousValue.md b/docs/usePreviousValue.md
index 49ac9bfd..038f0b83 100644
--- a/docs/usePreviousValue.md
+++ b/docs/usePreviousValue.md
@@ -1,15 +1,17 @@
# usePreviousValue
-Accepts a variable (*possibly a prop or a state*) and returns its previous render's value.
+A hook that receives a variable, which can be either a prop or a state, and outputs its previous value from the last render cycle
### Why? π‘
-- You want to keep track of the changes of your component state/props to decide whether it should update or not
+- Enables monitoring of changes to component state/props
+- Facilitates informed decisions on when to trigger component updates
### Basic Usage:
```jsx harmony
import { useState } from 'react';
+import { Typography, Tag } from 'antd';
import useInterval from 'beautiful-react-hooks/useInterval';
import usePreviousValue from 'beautiful-react-hooks/usePreviousValue';
@@ -20,12 +22,29 @@ const TestComponent = () => {
useInterval(() => setSeconds(1 + seconds), 1000);
return (
-
- {seconds}s
- The previous value of the state 'seconds' was: {prevSeconds}
+
+
+ {seconds}s
+
+
+ The previous value of the state 'seconds' was: {prevSeconds}
+
);
};
```
+
+
+### Types
+
+```typescript static
+/**
+ * On each render returns the previous value of the given variable/constant.
+ */
+declare const usePreviousValue: (value?: TValue | undefined) => TValue | undefined;
+export default usePreviousValue;
+
+```
+
\ No newline at end of file
diff --git a/docs/useQueryParam.md b/docs/useQueryParam.md
index b4305641..8c9752c0 100644
--- a/docs/useQueryParam.md
+++ b/docs/useQueryParam.md
@@ -1,17 +1,19 @@
# useQueryParam
+A hook built on top of React Router v5 that facilitate access and manipulation of query parameters.
+
### Why? π‘
-- to ease the process of modify the query string in the URL for the current location.
-- Works similar to the useState hook
-- it's NOT built on top of version 6 of react-router-dom's useSearchParams, it is therefore compatible with older version
+- Facilitates editing the query string in the URL for the current location
+- Functions similarly to the useState hook
+- Does not rely on version 6 of the useSearchParams function from react-router-dom, ensuring compatibility with older versions
### Basic Usage:
```jsx harmony
import { useState, useRef } from 'react';
import { HashRouter as Router } from 'react-router-dom'
-import { Input } from 'beautiful-react-ui'
+import { Typography, Tag, Input } from 'antd';
import useQueryParam from 'beautiful-react-hooks/useQueryParam';
const ExampleComponent = () => {
@@ -22,9 +24,11 @@ const ExampleComponent = () => {
})
return (
-
- Current value of 'foo' param is '{param}'
- setValue(nextValue)} />
+
+
+ Current value of 'foo' param is {param} <
+ /Typography.Paragraph>
+ setValue(e.targt.value)} />
);
};
@@ -33,3 +37,20 @@ const ExampleComponent = () => {
```
+
+
+### Types
+
+```typescript static
+export interface UseQueryParamOptions {
+ initialValue?: TValue;
+ replaceState?: boolean;
+}
+/**
+ * Ease the process of modify the query string in the URL for the current location.
+ */
+declare const useQueryParam: (key: string, options?: UseQueryParamOptions) => [TValue, (nextValue?: TValue | undefined) => void];
+export default useQueryParam;
+
+```
+
\ No newline at end of file
diff --git a/docs/useQueryParams.md b/docs/useQueryParams.md
index 2beac863..09f79d4b 100644
--- a/docs/useQueryParams.md
+++ b/docs/useQueryParams.md
@@ -13,7 +13,7 @@ Very similar to `useQueryParam` (mind the final 's'), it eases the process of ma
```jsx harmony
import { useState, useRef } from 'react';
import { HashRouter as Router } from 'react-router-dom'
-import { Button, Input } from 'beautiful-react-ui'
+import { Button, Typography, Input } from 'antd'
import useQueryParams from 'beautiful-react-hooks/useQueryParams';
const ExampleComponent = () => {
@@ -25,12 +25,17 @@ const ExampleComponent = () => {
const onClick = () => setFoos([4, 5, 6])
+ const Actions = [
+
+ Change to param to [4,5,6]
+
+ ]
+
return (
-
- Current value of 'foo[]' param is '{foos.join(',')}'
-
- Change to param to [4,5,6]
-
+
+
+ Current value of 'foo[]' param is '{foos.join(',')}'
+
);
};
@@ -39,3 +44,20 @@ const ExampleComponent = () => {
```
+
+
+### Types
+
+```typescript static
+export interface UseQueryParamsOptions {
+ initialValue?: TValue;
+ replaceState?: boolean;
+}
+/**
+ * Very similar to `useQueryParams`, it eases the process of manipulate a query string that handles multiple values
+ */
+declare const useQueryParams: (key: string, options?: UseQueryParamsOptions) => [TValue, (nextValue?: TValue | undefined) => void];
+export default useQueryParams;
+
+```
+
\ No newline at end of file
diff --git a/docs/useRenderInfo.md b/docs/useRenderInfo.md
index d3dee6a3..4445bc13 100644
--- a/docs/useRenderInfo.md
+++ b/docs/useRenderInfo.md
@@ -1,7 +1,7 @@
# useRenderInfo
-Takes a component name and prints information on how many time the component renders, at what time and how many seconds
-has passed since the last render.
+A hook that prints the number of renders for a given component, along with a timestamp of the most recent render and the time elapsed since
+the last render.
### Why? π‘
@@ -10,26 +10,25 @@ has passed since the last render.
### Basic Usage:
```jsx harmony
-import useInterval from 'beautiful-react-hooks/useInterval';
-import useRenderInfo from 'beautiful-react-hooks/useRenderInfo';
-
+import { Typography } from 'antd';
+import useInterval from 'beautiful-react-hooks/useInterval';
+import useRenderInfo from 'beautiful-react-hooks/useRenderInfo';
const RenderInfo = () => {
- const [seconds, setSeconds] = React.useState(0);
-
- // repeat the function each 1000ms
- useInterval(() => {
- setSeconds(1 + seconds);
- }, 1000);
+ const [seconds, setSeconds] = React.useState(0);
+ // repeat the function each 1000ms
+ useInterval(() => {
+ setSeconds(1 + seconds);
+ }, 1000);
- useRenderInfo('Module');
+ useRenderInfo('Module');
- return (
-
- Check the console!
-
- );
+ return (
+
+ Check the console!
+
+ );
};
@@ -38,24 +37,24 @@ const RenderInfo = () => {
### Custom logs:
```jsx harmony
-import useInterval from 'beautiful-react-hooks/useInterval';
-import useRenderInfo from 'beautiful-react-hooks/useRenderInfo';
-
+import { Typography } from 'antd';
+import useInterval from 'beautiful-react-hooks/useInterval';
+import useRenderInfo from 'beautiful-react-hooks/useRenderInfo';
const RenderInfo = () => {
- const [seconds, setSeconds] = React.useState(0);
- const info = useRenderInfo();
-
- // repeat the function each 1000ms
- useInterval(() => {
- setSeconds(1 + seconds);
- }, 1000);
-
- return (
-
- I'm not using the console, {info.sinceLast} seconds passed from the last render!
-
- );
+ const [seconds, setSeconds] = React.useState(0);
+ const info = useRenderInfo();
+
+ // repeat the function each 1000ms
+ useInterval(() => {
+ setSeconds(1 + seconds);
+ }, 1000);
+
+ return (
+
+ {info.sinceLast} seconds passed from the last render!
+
+ );
};
@@ -64,9 +63,31 @@ const RenderInfo = () => {
### Mastering the hook
#### β
When to use
-
+
- When debugging a component
#### π What not to do
- In production build, you don't want useless logs in console :)
+
+
+### Types
+
+```typescript static
+export interface RenderInfo {
+ readonly module: string;
+ renders: number;
+ timestamp: null | number;
+ sinceLast: null | number | '[now]';
+}
+/**
+ * useRenderInfo
+ * @param moduleName
+ * @param log
+ * @returns {{renders: number, module: *, timestamp: null}}
+ */
+declare const useRenderInfo: (moduleName?: string, log?: boolean) => RenderInfo;
+export default useRenderInfo;
+
+```
+
\ No newline at end of file
diff --git a/docs/useRequestAnimationFrame.md b/docs/useRequestAnimationFrame.md
index a60b3fd1..dab7f233 100644
--- a/docs/useRequestAnimationFrame.md
+++ b/docs/useRequestAnimationFrame.md
@@ -1,23 +1,26 @@
# useRequestAnimationFrame
-Takes care of running an animating function, provided as the first argument, while keeping track of its progress.
+A hook that facilitates the execution of javascript animations.
-When used `useRequestAnimationFrame` immediately starts a looping call the provided function by using
-[window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) under the hood.
+Upon usage, this hook initiates a recurring call to the provided function, using the
+built-in [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) function under the
+hood.
-The provided function receives the animation progress and a `next` function to be performed to keep the animation alive.
+The provided function received two arguments: the current progress of the animation and a next function that must be executed to sustain the
+animation.
-The loop ends when the animation progress reaches the value of 100. (or any other value provided as `finishAt`, check the options)
+The animation loop will terminate once the progress value reaches 100, although any other value can be specified using the `finishAt`
+option.
### Why? π‘
-- Easily manage a requestAnimationFrame function within a React component
+- Easily manage requestAnimationFrame within a React component
### Basic Usage
```jsx harmony
import { useRef } from 'react';
-import { Alert } from 'beautiful-react-ui';
+import { Alert } from 'antd';
import useRequestAnimationFrame from 'beautiful-react-hooks/useRequestAnimationFrame';
const AnimationExample = () => {
@@ -29,9 +32,9 @@ const AnimationExample = () => {
});
return (
-
+
);
@@ -42,13 +45,13 @@ const AnimationExample = () => {
### Options
-An object of options can be used as second argument to control the animation.
+The animation can be fine-tuned using an options object as the second argument.
-**Please note**: options.finishAt = -1 will cause an infinite animation
+Please note that setting `options.finishAt` to a value of `-1` will result in an infinite animation.
```jsx harmony
import { useRef } from 'react';
-import { Alert } from 'beautiful-react-ui';
+import { Alert } from 'antd';
import useRequestAnimationFrame from 'beautiful-react-hooks/useRequestAnimationFrame';
const AnimationExample = () => {
@@ -61,9 +64,9 @@ const AnimationExample = () => {
}, options);
return (
-
+
);
@@ -78,7 +81,7 @@ The hook returns an function to possibly set a callback when the animation finis
```jsx harmony
import { useRef, useState } from 'react';
-import { Alert, Paragraph } from 'beautiful-react-ui';
+import { Alert, Typography } from 'antd';
import useRequestAnimationFrame from 'beautiful-react-hooks/useRequestAnimationFrame';
const AnimationExample = () => {
@@ -92,11 +95,11 @@ const AnimationExample = () => {
onFinish(() => setIsFinished(true));
return (
-
+
- {isFinished && Animation completed! }
+ {isFinished && Animation completed! }
);
};
@@ -113,3 +116,22 @@ Control the speed of your animation by changing the increment value
#### β
When to use
- When in need to perform requestAnimationFrame without re-rendering the component on each frame
+
+
+### Types
+
+```typescript static
+import { type CallbackSetter, type GenericFunction } from './shared/types';
+export interface UseRequestAnimationFrameOpts {
+ increment?: number;
+ startAt?: number;
+ finishAt?: number;
+}
+/**
+ * Takes care of running an animating function, provided as the first argument, while keeping track of its progress.
+ */
+declare const useRequestAnimationFrame: (func: T, options?: UseRequestAnimationFrameOpts) => CallbackSetter;
+export default useRequestAnimationFrame;
+
+```
+
\ No newline at end of file
diff --git a/docs/useResizeObserver.md b/docs/useResizeObserver.md
index 3e386aa3..e9bbd91c 100644
--- a/docs/useResizeObserver.md
+++ b/docs/useResizeObserver.md
@@ -1,37 +1,41 @@
# useResizeObserver
-Uses the [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) API to observe changes to the size of the provided element and returns DOMRect data
+A hook that utilizes the [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) to monitor changes in the size
+of the supplied element and yields DOMRect data.
### Why? π‘
-- Asynchronously observes changes in the DOM Rect of the given HTML Element.
-- Takes care of cleaning the observable once the component is dismount.
+- Monitors variations asynchronously in the DOM Rect of the specified HTML Element.
+- Automatically disposes of the observer once the component unmounts.
### Basic Usage:
```jsx harmony
-import { useRef } from 'react';
-import useResizeObserver from 'beautiful-react-hooks/useResizeObserver';
+import { useRef } from 'react';
+import { Input } from 'antd';
+import useResizeObserver from 'beautiful-react-hooks/useResizeObserver';
const ResizeObserverExample = () => {
- const ref = useRef();
- const DOMRect = useResizeObserver(ref);
-
- return (
-
-
- {DOMRect && (
-
- Box width: {DOMRect.width}
- Box height: {DOMRect.height}
- Box left: {DOMRect.left}
- Box right: {DOMRect.right}
- Box top: {DOMRect.top}
- Box bottom: {DOMRect.bottom}
-
- )}
-
- );
+ const ref = useRef();
+ const DOMRect = useResizeObserver(ref);
+
+ return (
+
+
+
+
+ {DOMRect && (
+
+ Box width: {DOMRect.width}
+ Box height: {DOMRect.height}
+ Box left: {DOMRect.left}
+ Box right: {DOMRect.right}
+ Box top: {DOMRect.top}
+ Box bottom: {DOMRect.bottom}
+
+ )}
+
+ );
};
@@ -39,35 +43,53 @@ const ResizeObserverExample = () => {
### Debounce timout:
-useResizeObserver uses a debounced callback to avoid useless renders, by default the callback timeout is set to
-`250ms`.
-By passing a numeric value to useResizeObserver, other than the HTMLElement reference, it's possible to override the
-default timeout, as per the following example:
+This hook employs a debounced callback to prevent extra-renders. By default, the timeout for the callback is set to 250ms. However, it's
+possible to supersede the default timeout by passing a numeric value to useResizeObserver, in lieu of the HTMLElement reference.
```jsx harmony
-import { useRef } from 'react';
-import useResizeObserver from 'beautiful-react-hooks/useResizeObserver';
+import { useRef } from 'react';
+import useResizeObserver from 'beautiful-react-hooks/useResizeObserver';
const ResizeObserverExample = () => {
- const ref = useRef();
- const DOMRect = useResizeObserver(ref, 1000);
-
- return (
-
-
- {DOMRect && (
-
- Box width: {DOMRect.width}
- Box height: {DOMRect.height}
- Box left: {DOMRect.left}
- Box right: {DOMRect.right}
- Box top: {DOMRect.top}
- Box bottom: {DOMRect.bottom}
-
- )}
-
- );
+ const ref = useRef();
+ const DOMRect = useResizeObserver(ref, 1000);
+
+ return (
+
+
+
+
+ {DOMRect && (
+
+ Box width: {DOMRect.width}
+ Box height: {DOMRect.height}
+ Box left: {DOMRect.left}
+ Box right: {DOMRect.right}
+ Box top: {DOMRect.top}
+ Box bottom: {DOMRect.bottom}
+
+ )}
+
+ );
};
```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+export type DOMRectValues = Pick;
+/**
+ * Uses the ResizeObserver API to observe changes within the given HTML Element DOM Rect.
+ * @param elementRef
+ * @param debounceTimeout
+ * @returns {undefined}
+ */
+declare const useResizeObserver: (elementRef: RefObject, debounceTimeout?: number) => DOMRectValues | undefined;
+export default useResizeObserver;
+
+```
+
\ No newline at end of file
diff --git a/docs/useSearchQuery.md b/docs/useSearchQuery.md
index 553f08be..8a882e39 100644
--- a/docs/useSearchQuery.md
+++ b/docs/useSearchQuery.md
@@ -1,25 +1,28 @@
# useSearchQuery
+A hook built on top of React Router v5 that facilitate access and manipulation of the 'search' query parameter.
+
### Why? π‘
-- to ease the process of modify the 'search' query string in the URL for the current location.
-- Works similar to useState hook
-- built on top of useQueryParam
+- Facilitates editing the 'search' query string in the URL for the current location
+- Functions similarly to the useState hook
### Basic Usage:
```jsx harmony
import { useState, useRef } from 'react';
import { HashRouter as Router } from 'react-router-dom'
-import { Input } from 'beautiful-react-ui'
+import { Input, Typography, Tag } from 'antd'
import useSearchQuery from 'beautiful-react-hooks/useSearchQuery';
const ExampleComponent = () => {
const [searchValue, setSearch] = useSearchQuery('initial-value')
return (
-
- Current value of search param is '{searchValue}'
+
+
+ Current value of search param is {searchValue}
+
setSearch(nextValue)} />
);
@@ -29,3 +32,17 @@ const ExampleComponent = () => {
```
+
+
+### Types
+
+```typescript static
+/**
+ * Ease the process of modify the 'search' query string in the URL for the current location.
+ * It's just a shortcut/wrapper around useQueryParam
+ */
+declare const useSearchQuery: (initialValue?: TSearchKey | undefined, replaceState?: boolean) => [TSearchKey, (nextValue?: TSearchKey | undefined) => void];
+export default useSearchQuery;
+
+```
+
\ No newline at end of file
diff --git a/docs/useSessionStorage.md b/docs/useSessionStorage.md
index 6bc29e9f..1e52f6a9 100644
--- a/docs/useSessionStorage.md
+++ b/docs/useSessionStorage.md
@@ -1,32 +1,37 @@
# useSessionStorage
-A hook for storing values into [Session Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
+A hook that enables effortless storage and retrieval of values in the
+browser's [Session Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
### π‘ Why?
-- A quick way to use the `sessionStorage` in your React components.
+- A fast and efficient method to implement the `sessionStorage` functionality in your React components
### Basic Usage:
```jsx harmony
import React, { useCallback } from 'react';
-import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
+import { Pill, Paragraph, Icon } from 'antd';
import useSessionStorage from 'beautiful-react-hooks/useSessionStorage';
const NotificationBadgeExample = ({ notifications }) => {
const [notificationCount, setNotificationCount] = useSessionStorage('demo-notification-count', notifications);
-
+
const clearNotifications = useCallback(() => {
setNotificationCount(0);
}, [notificationCount]);
+ const Actions = [
+
+ You've got {notificationCount} new messages
+
+ ]
+
return (
-
- Click on the badge to clear from the session storage
-
-
- You've got {notificationCount} new messages
-
+
+
+ Click on the following button to clear data from the demo-notification-count session storage key.
+
)
};
@@ -34,6 +39,14 @@ const NotificationBadgeExample = ({ notifications }) => {
```
+### Interface
+
+```typescript
+type SetValue = (value: TValue | ((previousValue: TValue) => TValue)) => void
+
+declare const useSessionStorage: (storageKey: string, defaultValue?: any) => [TValue, SetValue]
+```
+
### Mastering the hooks
#### β
When to use
@@ -43,3 +56,16 @@ const NotificationBadgeExample = ({ notifications }) => {
#### π When not to use
- Do not use this hook as a state manager, the `sessionStorage` is meant to be used for small pieces of data
+
+
+### Types
+
+```typescript static
+/**
+ * Save a value on session storage
+ */
+declare const useSessionStorage: (storageKey: string, defaultValue?: any) => [TValue | null, (value: TValue | ((previousValue: TValue) => TValue)) => void];
+export default useSessionStorage;
+
+```
+
\ No newline at end of file
diff --git a/docs/useSpeechSynthesis.md b/docs/useSpeechSynthesis.md
index 8c310daf..fec1dd8d 100644
--- a/docs/useSpeechSynthesis.md
+++ b/docs/useSpeechSynthesis.md
@@ -1,30 +1,29 @@
# useSpeechSynthesis
-
- [This is still an experimental feature](https://developer.mozilla.org/en-US/docs/MDN/Contribute/Guidelines/Conventions_definitions#Experimental)
-
-
-Enables the possibility to perform a text-to-speach (with different voices) operation in your React component by using the [Web_Speech_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API).
+A hook that allows you to integrate text-to-speech functionality (with varying voices) within your React component by leveraging
+the [Web_Speech_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API).
### Why? π‘
-- wraps the business logic of handling the Web Speech API into a single function
+- Abstracts the implementation details of the Web Speech API into a single reusable function.
### Basic Usage:
```jsx harmony
-import { Button, Input } from 'beautiful-react-ui';
-import useSpeechSynthesis from 'beautiful-react-hooks/useSpeechSynthesis';
+import { Button, Space, Input } from 'antd';
+import useSpeechSynthesis from 'beautiful-react-hooks/useSpeechSynthesis';
const SpeechSynthesisDemo = () => {
const [name, setName] = React.useState('Antonio');
- const { speak } = useSpeechSynthesis(`Hello, ${name}`);
-
+ const { speak } = useSpeechSynthesis(`Hello, ${name}`);
+
return (
-
- setName(v)} placeholder="Name" fluid />
- Greet!
-
+
+
+ setName(v)} placeholder="Name" fluid />
+ Say hello...
+
+
);
};
@@ -36,38 +35,37 @@ const SpeechSynthesisDemo = () => {
`useSpeechSynthesis` receives an optional options object as second parameter to possibly define a custom voice.
```jsx harmony
-import { Button, Input, Select } from 'beautiful-react-ui';
-import useSystemVoices from 'beautiful-react-hooks/useSystemVoices';
-import useSpeechSynthesis from 'beautiful-react-hooks/useSpeechSynthesis';
+import { Button, Input, Space, Select } from 'antd';
+import useSystemVoices from 'beautiful-react-hooks/useSystemVoices';
+import useSpeechSynthesis from 'beautiful-react-hooks/useSpeechSynthesis';
const VoiceSelector = ({ onVoiceChange }) => {
- const [current, setVoice] = React.useState(0);
- const voices = useSystemVoices();
- const options = voices.map(({ name }, index) => ({ label: name, value: index }));
+ const [current, setVoice] = React.useState(0);
+ const voices = useSystemVoices();
+ const options = voices.map(({ name }, index) => ({ label: name, value: index }));
- React.useEffect(() => {
+ React.useEffect(() => {
onVoiceChange(voices[current]);
- }, [current]);
+ }, [current]);
- return (
-
- );
+ return (
+
+ );
};
-
const SpeechSynthesisDemo = () => {
const [voice, setVoice] = React.useState();
const [name, setName] = React.useState('my friend');
- const { speak } = useSpeechSynthesis(`Hello, ${name}`, { voice });
-
+ const { speak } = useSpeechSynthesis(`Hello, ${name}`, { voice });
+
return (
-
-
-
- setName(next)} placeholder="Your name" fluid style={{marginBottom: '1rem'}} />
-
- Greet!
-
+
+
+ setName(next)} placeholder="Your name" />
+
+ Greet!
+
+
);
};
@@ -79,18 +77,20 @@ const SpeechSynthesisDemo = () => {
`useSpeechSynthesis` receives an optional options object as second parameter to possibly define a custom `rate` and `pitch`
```jsx harmony
-import { Button, Input } from 'beautiful-react-ui';
-import useSpeechSynthesis from 'beautiful-react-hooks/useSpeechSynthesis';
+import { Button, Input, Space } from 'antd';
+import useSpeechSynthesis from 'beautiful-react-hooks/useSpeechSynthesis';
const SpeechSynthesisDemo = () => {
const [name, setName] = React.useState('Antonio');
- const { speak } = useSpeechSynthesis(`Hello, ${name}`, { rate: 10, pitch: 15, volume: 2 });
-
+ const { speak } = useSpeechSynthesis(`Hello, ${name}`, { rate: 1.2, pitch: 1.2, volume: 1.2 });
+
return (
-
- setName(v)} placeholder="Name" fluid />
- Greet!
-
+
+
+ setName(next)} placeholder="Your name" />
+ Greet!
+
+
);
};
@@ -100,10 +100,37 @@ const SpeechSynthesisDemo = () => {
### Mastering the hook
#### β
When to use
-
-- When in need of a text-to-speech functionality using the [Web_Speech_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API).
+- When you want to incorporate text-to-speech functionality in your React application by utilizing
+ the [Web_Speech_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API)
+
+
+### Types
+
+```typescript static
+/**
+ * The options that can be passed to the hook
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance
+ */
+export interface UseSpeechSynthesisOptions {
+ rate?: number;
+ pitch?: number;
+ volume?: number;
+ voice?: SpeechSynthesisVoice;
+}
+/**
+ * The result of the hook
+ */
+export interface SpeechSynthesisResult {
+ readonly speak: () => void;
+ readonly speechSynthUtterance: SpeechSynthesisUtterance;
+}
+/**
+ * Enables the possibility to perform a text-to-speech (with different voices) operation in your
+ * React component by using the Web_Speech_API
+ */
+declare const useSpeechSynthesis: (text: string, options?: UseSpeechSynthesisOptions) => Readonly;
+export default useSpeechSynthesis;
-#### π When not to use
-
-- In production...yet. This is still an **experimental feature**
+```
+
\ No newline at end of file
diff --git a/docs/useSwipe.md b/docs/useSwipe.md
index 0a6eaf80..aab79253 100644
--- a/docs/useSwipe.md
+++ b/docs/useSwipe.md
@@ -1,13 +1,13 @@
# useSwipe
-Returns the state of the swipe gesture both on mobile or desktop.
+A hook that provides access to the current state of swipe gestures, regardless of whether the user is on a mobile or desktop device
### Why? π‘
-- allows to easily receive the last swipe information
-- takes care of adding the listeners both for mouse and touch events globally or to the defined target
-- takes care of cleaning the listener when the component will unmount
-- allows performing abstractions on swipe related logics
+- facilitates the retrieval of the most recent swipe data
+- registers global or target-specific listeners for both mouse and touch events
+- automatically removes listeners upon unmounting of the component
+- enables abstraction of swipe-related logic
### Basic Usage:
@@ -23,8 +23,8 @@ const SwipeReporter = () => {
const showDetail = swipeState.count > 0 || swipeState.swiping;
return (
-
-
+
+
Swipe me!
{showDetail && (
@@ -45,7 +45,7 @@ const SwipeReporter = () => {
### Global events
-Avoid providing any argument to `useSwipe`
+To register global listeners, simply invoke the hook without passing any arguments
```jsx harmony
import { useRef, useState } from 'react';
@@ -56,8 +56,8 @@ const SwipeReporter = () => {
const showDetail = swipeState.count > 0 || swipeState.swiping;
return (
-
-
+
+
Swipe everywehere you want!
{showDetail && (
@@ -93,8 +93,8 @@ const SwipeReporter = () => {
const showDetail = swipeState.count > 0 || swipeState.swiping;
return (
-
-
+
+
Swipe me, horizontally...
{showDetail && (
@@ -112,3 +112,37 @@ const SwipeReporter = () => {
```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+import { type Direction } from './shared/swipeUtils';
+/**
+ * The options that can be passed to the hook
+ */
+export interface UseSwipeOptions {
+ direction?: 'both' | 'horizontal' | 'vertical';
+ threshold?: number;
+ preventDefault?: boolean;
+ passive?: boolean;
+}
+/**
+ * The result of the hook
+ */
+export interface SwipeState {
+ swiping: boolean;
+ direction?: Direction;
+ alphaX: number;
+ alphaY: number;
+ count: number;
+}
+/**
+ * useSwipe hook
+ */
+declare const useSwipe:
(targetRef?: RefObject | undefined, options?: UseSwipeOptions) => SwipeState;
+export default useSwipe;
+
+```
+
\ No newline at end of file
diff --git a/docs/useSwipeEvents.md b/docs/useSwipeEvents.md
index 172d9004..d350d6a5 100644
--- a/docs/useSwipeEvents.md
+++ b/docs/useSwipeEvents.md
@@ -1,16 +1,16 @@
# useSwipeEvents
-Returns a set of handler setters to control swipe events.
-It possibly accepts a DOM ref to target the event(s) to. If the target is not provided the events will be globally attached to
-the `document` object.
+A hook that provides a set of callback setters to manage swipe events. It can optionally receive a DOM ref to specify the target element for
+the event(s). If no target is provided, the events will be attached globally to the `document` object.
-Available handler setters: `onSwipeLeft`, `onSwipeRight`, `onSwipeUp`, `onSwipeDown`, `onSwipeStart`, `onSwipeMove`, `onSwipeEnd`;
+Available callback setters: `onSwipeLeft`, `onSwipeRight`, `onSwipeUp`, `onSwipeDown`, `onSwipeStart`, `onSwipeMove`, `onSwipeEnd`;
### Why? π‘
-- takes care of adding the mouse/touch listeners to handle swipe both globally or to a defined target
-- takes care of cleaning the listener when the component unmounts
-- allows performing abstractions on swipe related events
+- simplifies the handling of swipe gestures by adding mouse and touch listeners for swipe events globally or to a defined target.
+- handles the cleanup of listeners when the component unmounts, avoiding memory leaks and unwanted behaviors.
+- enables the creation of abstractions on swipe-related events, allowing you to focus on implementing your desired functionality without
+ worrying about the details of swipe detection.
### Basic Usage:
@@ -24,16 +24,16 @@ const SwipeReporter = () => {
const ref = useRef();
const { onSwipeLeft, onSwipeRight, onSwipeUp, onSwipeMove, onSwipeDown } = useSwipeEvents(ref);
const [lastSwipeInfo, setLastSwipeInfo] = useState();
-
+
onSwipeLeft(setLastSwipeInfo);
onSwipeRight(setLastSwipeInfo);
onSwipeUp(setLastSwipeInfo);
onSwipeDown(setLastSwipeInfo);
onSwipeMove(console.log);
-
+
return (
-
+
Swipe me!
@@ -66,7 +66,7 @@ const SwipeReporter = () => {
onSwipeDown(setLastSwipeInfo);
return (
-
+
Swipe around!
@@ -81,7 +81,6 @@ const SwipeReporter = () => {
```
-
### Options
* **threshold**: defines the minimum amount of pixel "to move" to start swiping. _default: 15_.
@@ -103,7 +102,7 @@ const SwipeReporter = () => {
onSwipeDown(setLastSwipeInfo);
return (
-
+
Swipe me!
@@ -117,3 +116,47 @@ const SwipeReporter = () => {
```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+import { type CallbackSetter } from './shared/types';
+/**
+ * The swipe event state interface
+ */
+export interface SwipeEventState {
+ clientX?: number;
+ clientY?: number;
+ direction: 'right' | 'left' | 'up' | 'down';
+ alphaX: number;
+ alphaY: number;
+}
+/**
+ * The result of the hook
+ */
+interface UseSwipeEventsReturn {
+ onSwipeLeft: CallbackSetter;
+ onSwipeRight: CallbackSetter;
+ onSwipeUp: CallbackSetter;
+ onSwipeDown: CallbackSetter;
+ onSwipeMove: CallbackSetter;
+ onSwipeStart: CallbackSetter;
+ onSwipeEnd: CallbackSetter;
+}
+export interface UseSwipeEventsOpts {
+ threshold?: number;
+ preventDefault?: boolean;
+ passive?: boolean;
+}
+/**
+ * useSwipeEvents
+ * @param ref
+ * @param options
+ */
+declare const useSwipeEvents: (ref?: RefObject | undefined, options?: UseSwipeEventsOpts) => Readonly;
+export default useSwipeEvents;
+
+```
+
\ No newline at end of file
diff --git a/docs/useSystemVoices.md b/docs/useSystemVoices.md
index 0cff92cd..4815a6e3 100644
--- a/docs/useSystemVoices.md
+++ b/docs/useSystemVoices.md
@@ -1,45 +1,56 @@
# useSystemVoices
-
- [This is still an experimental feature](https://developer.mozilla.org/en-US/docs/MDN/Contribute/Guidelines/Conventions_definitions#Experimental)
-
+A hook that returns all the available voices on the system.
-A side effect to retrieve all the available system voices using the [Web_Speech_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API).
+**Note:** it's important to note that the purpose of this hook is to maintain backward compatibility with a previous version of the library
+that utilized a non-stable version of the Web Speech API. In that version, voices were returned asynchronously.
+
+If you are currently using a version of the library that does not require this hook, you can simply run:
+
+```typescript static
+const voices = window.speechSynthesis.getVoices()
+```
### Why? π‘
- At the moment, the `window.speechSynthesis.getVoices` function returns all the available system voices, but since
-it does it asynchronously [the returning value is an empty array until a second call is performed](https://w3c.github.io/speech-api/speechapi-errata.html).
-This hook manage the side-effect of correctly retrieve all the available system voices.
+ it does it
+ asynchronously [the returning value is an empty array until a second call is performed](https://w3c.github.io/speech-api/speechapi-errata.html)
+ this hook manage the side-effect of correctly retrieve all the available system voices.
### Basic Usage:
```jsx harmony
-import { List, Title } from 'beautiful-react-ui';
-import useSystemVoices from 'beautiful-react-hooks/useSystemVoices';
+import { List, Typography } from 'antd';
+import useSystemVoices from 'beautiful-react-hooks/useSystemVoices';
const SpeechSynthesisDemo = () => {
- const voices = useSystemVoices();
+ const voices = useSystemVoices();
return (
-
- System voices
-
- {voices.map(({ name, lang }) => {name} - {lang} )}
-
-
+
+ System voices
+
+ {voices.map(({ name, lang }) => {name} - {lang} )}
+
+
);
};
```
-### Mastering the hooks
+
+### Types
+
+```typescript static
+/**
+ * Returns all the available voices on the system.
+ * This hook is here to backward compatibility with the previous version of the library that was using
+ * a different non-stable version of the Web Speech API.
+ */
+declare const useSystemVoices: () => SpeechSynthesisVoice[];
+export default useSystemVoices;
-#### β
When to use
-
-- When you need to easily get all the system languages from the [Web_Speech_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API).
-
-#### π When not to use
-
-- In production...yet. This is still an **experimental feature**
+```
+
\ No newline at end of file
diff --git a/docs/useThrottledCallback.md b/docs/useThrottledCallback.md
index aedc4cd9..6ce90bfc 100644
--- a/docs/useThrottledCallback.md
+++ b/docs/useThrottledCallback.md
@@ -1,16 +1,17 @@
# useThrottledCallback
-Accepts a function and returns a new memoized version of that function that waits the defined time before allowing the next execution. If
-time is not defined, its default value will be 250ms.
+A hook that takes in a function as an argument and returns a new memoized version of the function that limits its invocation to once per
+specified time interval, measured in milliseconds. By default, the time interval is set to 250ms if not defined.
### Why? π‘
-- Controls how many times we allow a function to be executed over time regardless the number of renders the component is performing
+- Manages the frequency of function execution, irrespective of the number of times a component is rendered.
## Basic Usage
```jsx harmony
import { useEffect, useState } from 'react';
+import { Space, Alert, Typography, Tag } from 'antd';
import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -35,9 +36,15 @@ const ThrottledFnComponent = () => {
});
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -52,6 +59,7 @@ under the hood, you can possibly define the callback dependencies.
```jsx harmony
import { useState } from 'react';
+import { Space, Alert, Typography, Tag } from 'antd';
import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -86,6 +94,7 @@ A custom throttled time can be easily defined as follows (500ms)
```jsx harmony
import { useState } from 'react';
+import { Space, Alert, Typography, Tag } from 'antd';
import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -104,9 +113,15 @@ const ThrottledFnComponent = (props) => {
onWindowResize(onWindowResizeHandler);
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -121,6 +136,7 @@ under the hood, you can possibly define few options to customise its behaviour.
```jsx harmony
import { useState } from 'react';
+import { Space, Alert, Typography, Tag } from 'antd';
import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
@@ -143,9 +159,15 @@ const ThrottledFnComponent = () => {
onWindowResize(onWindowResizeHandler);
return (
-
- window width: {width}
- window height: {height}
+
+
+
+
+
+ window width: {width}
+ window height: {height}
+
+
);
};
@@ -155,12 +177,28 @@ const ThrottledFnComponent = () => {
#### β
Pro tip:
-To deep understanding the differences between `throttle` and `debounce`, what they are and when to use this functions please
+To deep understanding the differences between `throttle` and `debounce`, what they are and when to use them please
read "[Debouncing and Throttling Explained Through Examples](https://css-tricks.com/debouncing-throttling-explained-examples/)"
by [David Corbacho](https://twitter.com/dcorbacho)
-### Mastering the hook
+
+### Types
+
+```typescript static
+///
+import { type DependencyList } from 'react';
+import { type GenericFunction } from './shared/types';
+interface ThrottleSettings {
+ leading?: boolean | undefined;
+ trailing?: boolean | undefined;
+}
+/**
+ * Accepts a function and returns a new throttled yet memoized version of that same function that waits the defined time
+ * before allowing the next execution.
+ * If time is not defined, its default value will be 250ms.
+ */
+declare const useThrottledCallback: (fn: TCallback, dependencies?: DependencyList, wait?: number, options?: ThrottleSettings) => import("lodash").DebouncedFunc;
+export default useThrottledCallback;
-#### β
When to use
-
-- The classic example would be an infinite scroll over a paginated API call
+```
+
\ No newline at end of file
diff --git a/docs/useTimeout.md b/docs/useTimeout.md
index 093f3469..1a233ac6 100644
--- a/docs/useTimeout.md
+++ b/docs/useTimeout.md
@@ -1,19 +1,20 @@
# useTimeout
-An async-utility hook that accepts a callback `function` and a `delay time` (*in milliseconds*), then delays the execution of the given
-function by the defined time.
+A hook that facilitates the utilization of the `setTimeout` function in React function components. This hook receives a callback function
+and a delay duration as inputs, and subsequently, executes the given function at after the specified delay time.
### π‘ Why?
-- takes care of performing the given callback regardless the component re-renders;
-- cancels the timeout when component unmount (or not, depends by the defined options);
-- returns the timeout state (cleared/not cleared)
-- returns a method to possibly cancel the set timeout (cause the component re-render)
+- Ensures that the given callback is executed reliably, even when the component re-renders;
+- Automatically cancels the timeout when the component unmounts (although this behavior can be modified by adjusting the options);
+- Provides information about the current state of the timeout (whether it has been cleared or not);
+- Offers a method to cancel the timeout, which can trigger a re-render of the component if desired.
### Basic Usage:
```jsx harmony
import { useState } from 'react';
+import { Typography } from 'antd'
import useTimeout from 'beautiful-react-hooks/useTimeout';
const DelayedContentComponent = () => {
@@ -25,8 +26,8 @@ const DelayedContentComponent = () => {
}, 2000);
return (
-
- Content will show in 2 seconds...
+
+ Content will show in 2 seconds...
{showContent && π°
}
);
@@ -43,6 +44,7 @@ The hook returns the state of the timeout (a boolean, cleared/not cleared) and a
```jsx harmony
import { useState } from 'react';
+import { Typography, Button } from 'antd'
import useTimeout from 'beautiful-react-hooks/useTimeout';
const DelayedContentComponent = () => {
@@ -52,11 +54,11 @@ const DelayedContentComponent = () => {
}, 5000);
return (
-
- Content will show in 5 seconds...
+
+ Content will show in 5 seconds...
{showContent && π°
}
- {!isCleared && Press here to cancel timeout }
- {isCleared && Cleared
}
+ {!isCleared && Press here to cancel timeout }
+ {isCleared && Cleared }
);
};
@@ -66,7 +68,7 @@ const DelayedContentComponent = () => {
### Options:
-`useTimeout` might accept a options object provided as eventual parameter.
+`useTimeout` might accept an options object provided as eventual parameter.
#### cancelOnUnmount:
@@ -76,6 +78,7 @@ Defines whether the timeout should be cleared on unmount.
```jsx harmony
import { useState } from 'react';
+import { Typography } from 'antd';
import useTimeout from 'beautiful-react-hooks/useTimeout';
const DelayedContentComponent = () => {
@@ -85,8 +88,8 @@ const DelayedContentComponent = () => {
useTimeout(() => setShowContent(true), 3000, options);
return (
-
- Content will show in 3 seconds but not be cleared on unmount
+
+ Content will show in 3 seconds but not be cleared on unmount
{showContent && π°
}
);
@@ -99,8 +102,26 @@ const DelayedContentComponent = () => {
#### β
When to use
-- If in need to perform a function after a specified number of milliseconds regardless the component re-renders
+- when there is a requirement to execute a function after a specific number of milliseconds, without being affected by component re-renders
#### π When not to use
-- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+- Avoid using this hook for asynchronous operations since it violates the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+
+
+### Types
+
+```typescript static
+import { type GenericFunction } from './shared/types';
+export interface UseTimeoutOptions {
+ cancelOnUnmount?: boolean;
+}
+/**
+ * An async-utility hook that accepts a callback function and a delay time (in milliseconds), then delays the
+ * execution of the given function by the defined time.
+ */
+declare const useTimeout: (fn: TCallback, milliseconds: number, options?: UseTimeoutOptions) => [boolean, () => void];
+export default useTimeout;
+
+```
+
\ No newline at end of file
diff --git a/docs/useToggle.md b/docs/useToggle.md
index c3fb6a71..5022259d 100644
--- a/docs/useToggle.md
+++ b/docs/useToggle.md
@@ -1,25 +1,31 @@
# useToggle
-A quick and safe utility for boolean states
+A hook that encapsulates the business logic of dealing with boolean values.
+
+Provides a higher-level interface for dealing with boolean logic in React function component.
### Why? π‘
-- frequent boolean states causes code duplication, this hook wraps-up the business logic of implementing a single boolean state
+- Having multiple boolean states in an application often leads to code redundancy. This hook consolidates the implementation details of a
+ singular boolean state, promoting code reusability and reducing code bloat.
### Basic Usage:
```jsx harmony
-import useToggle from 'beautiful-react-hooks/useToggle';
-import { Button } from 'beautiful-react-ui'
+import { Typography, Tag, Button } from 'antd'
+import useToggle from 'beautiful-react-hooks/useToggle'
const ComponentWillUnmount = () => {
const [value, toggleValue] = useToggle()
+ const tagColor = value ? 'green' : 'red'
return (
-
- Toggle is {value ? 'on' : 'off'}
- toggle value
-
+
+
+ Toggle is {value ? 'on' : 'off'}
+
+ toggle value
+
);
};
@@ -29,19 +35,35 @@ const ComponentWillUnmount = () => {
### Initial state
```jsx harmony
-import useToggle from 'beautiful-react-hooks/useToggle';
-import { Button } from 'beautiful-react-ui'
+import { Button, Typography, Tag } from 'antd'
+import useToggle from 'beautiful-react-hooks/useToggle'
const ComponentWillUnmount = () => {
const [value, toggleValue] = useToggle(true)
+ const tagColor = value ? 'green' : 'red'
return (
-
- Toggle is {value ? 'on' : 'off'}
- toggle value
-
+
+
+ Toggle is {value ? 'on' : 'off'}
+
+ toggle value
+
);
};
```
+
+
+### Types
+
+```typescript static
+/**
+ * A quick and simple utility for toggle states
+ */
+declare const useToggle: (initialState?: boolean) => [boolean, () => void];
+export default useToggle;
+
+```
+
\ No newline at end of file
diff --git a/docs/useTouch.md b/docs/useTouch.md
index cacb4698..cbcecc6a 100644
--- a/docs/useTouch.md
+++ b/docs/useTouch.md
@@ -1,16 +1,16 @@
# useTouch
-Returns an array where the first item is the touch state from [useTouchState](./useTouchState.md) and the second item is the object of
-handler setters from [useTouchEvents](./useTouchEvents.md).
+A hook that combines the functionalities of [useTouchState](./useTouchState.md) and [useTouchEvents](./useTouchEvents.md), returning an
+array where the first item is the mouse state and the second item is a wrapper of all the handler-setters.
-It is intended as a shortcut to those hooks.
+`useTouch` is intended as a shortcut to avoid the need for using both `useTouch`State and `useTouch`Events separately.
### Why? π‘
-- allow to easily receive the touches state
-- takes care of adding the touch events listeners globally or to the defined target
-- takes care of cleaning the listener when the component will unmount
-- allows performing abstractions on mouse related events
+- Provides an easy way to obtain the mouse position
+- Automatically adds mouse event listeners either globally or to the specified target element
+- Automatically removes the listeners when the component unmounts
+- Enables abstractions on mouse-related events
### Basic Usage:
@@ -18,6 +18,7 @@ Provide a DOM ref as first parameter to `useTouch`
```jsx harmony
import { useRef, useState } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useTouch from 'beautiful-react-hooks/useTouch';
const TouchReporter = () => {
@@ -27,16 +28,19 @@ const TouchReporter = () => {
onTouchStart(() => setShowCoords(true));
onTouchEnd(() => setShowCoords(false));
-
+
return (
-
-
- Move mouse over me to get its current coordinates:
- {showCoords && touches[0] && (
-
{touches[0].clientX}, {touches[0].clientY}
- )}
-
-
+
+
+
+
+ {showCoords && touches.length > 0 && ([
+ Touch X: {touches[0].clientX} ,
+ Touch Y: {touches[0].clientY}
+ ])}
+
+
+
);
};
@@ -45,10 +49,11 @@ const TouchReporter = () => {
### Global events
-Avoid providing any argument to `useTouch`
+If no ref is provided to `useTouch` it will use the window global object assign the events to
```jsx harmony
import { useRef, useState } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useTouch from 'beautiful-react-hooks/useTouch';
const TouchReporter = () => {
@@ -57,16 +62,17 @@ const TouchReporter = () => {
onTouchStart(() => setShowCoords(true));
onTouchEnd(() => setShowCoords(false));
-
+
return (
-
-
- Move mouse over me to get its current coordinates:
- {showCoords && touches[0] && (
-
{touches[0].clientX}, {touches[0].clientY}
- )}
-
-
+
+
+
+ {touches.length > 0 && ([
+ Touch X: {touches[0].clientX} ,
+ Touch Y: {touches[0].clientY}
+ ])}
+
+
);
};
@@ -77,25 +83,39 @@ const TouchReporter = () => {
#### β
When to use
-- If in need to get the mouse current position
-- If in need to abstract some mouse related logic into a custom hooks
+- When you need to abstract touch-related logics into custom hooks(s)
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any effect but changing the handler possibly leading to bugs in
- your code.
-- Absolutely avoid using `useTouch` handler setters to replace the standard mouse handler props.
-- `useTouch` is meant to be used to abstract more complex hooks that need to control the mouse, for example: a drag n drop hook.
-- Using `useTouch` handlers instead of the classic props approach it's just as bad as it sounds since you'll lose the React SyntheticEvent
- performance boost.
-- If you were doing something like the following, please keep doing it:
+- Do not use the returned callback setters asynchronously, as doing so will have no effect and may result in bugs in your code.
+- Avoid using `useTouch` callback setters to replace standard mouse handler props.
+- `useTouch` is designed to be used for abstracting more complex hooks that need to control the mouse, such as a drag-and-drop hook.
+- Using `useTouch` handlers instead of the classic props approach will result in decreased performance due to the loss of the React
+ SyntheticEvent performance boost. If you were using a classic props approach before, continue to do so.
```jsx harmony static noedit
const MyComponent = (props) => {
const { mouseDownHandler } = props;
return (
-
+
);
};
-```
+```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+import { type UseTouchEventsReturn } from './useTouchEvents';
+/**
+ * Returns an array where the first item is the touch state from the `useTouchState` hook and the second item
+ * is the object of callback setters from the `useTouchEvents` hook.
+ * It is intended as a shortcut to those hooks.
+ */
+declare const useTouch: (targetRef?: RefObject | undefined) => [TouchList, Readonly];
+export default useTouch;
+
+```
+
\ No newline at end of file
diff --git a/docs/useTouchEvents.md b/docs/useTouchEvents.md
index 1643a355..0c6263cd 100644
--- a/docs/useTouchEvents.md
+++ b/docs/useTouchEvents.md
@@ -1,19 +1,19 @@
# useTouchEvents
-Returns a set of handler setters to control touch events (*onTouchStart, onTouchMove, onTouchEnd*).
-It possibly accepts a DOM ref to target the event(s) to.
-If the target is not provided the events will be globally attached to the `document` object.
+A hook that provides an easy way to manage touch events by returning a set of callback setters. The returned setters allow control over
+various mouse events including `onTouchStart`, `onTouchMove`, `onTouchEnd`;
-Available handler setters: `onTouchStart`, `onTouchMove`, `onTouchEnd`;
+The hook optionally accepts a reference to a DOM element to target the desired event(s) to. If no target is provided, the events will be
+attached globally to the document object.
-**Please note:** the returned handler setters should be immediately invoked in the component's body, do not try to call this functions
-asynchronously.
+It is important to note that the returned callback setters should be immediately invoked within the component's body, and should not be
+called asynchronously.
### Why? π‘
-- takes care of adding the touch events listeners globally or to a defined target
-- takes care of cleaning the listener when the component unmounts
-- allows performing abstractions on touch related events
+- handles the addition of touch event listeners either globally or to a specified target.
+- takes care of cleaning up the listeners when the component is unmounted.
+- enables the implementation of abstractions on touch-related events.
### Basic Usage:
@@ -21,6 +21,7 @@ Provide a DOM ref as first parameter to `useTouchEvents`
```jsx harmony
import { useRef, useState } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useTouchEvents from 'beautiful-react-hooks/useTouchEvents';
const MyComponent = () => {
@@ -36,7 +37,7 @@ const MyComponent = () => {
onTouchMove((event) => {
if (touching) {
const { clientX, clientY } = event.touches[0];
-
+
setCoordinates([clientX, clientY]);
}
});
@@ -46,14 +47,16 @@ const MyComponent = () => {
});
return (
-
-
- Touch here! touching?: {touching ? 'yes' : 'no'}
- {touching && (
-
Coordinates: { coordinates[0] }, { coordinates[1] }
- )}
-
-
+
+
+
+
+ Is touching: {touching ? 'no' : 'yes'}
+ Touch X: {coordinates[0]}
+ Touch Y: {coordinates[1]}
+
+
+
);
};
@@ -62,10 +65,11 @@ const MyComponent = () => {
### Global events
-Avoid providing any argument to `useTouchEvents` to attach the events globally
+If no ref is provided to `useTouchEvents` it will use the window global object assign the events to
```jsx harmony
import { useState } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useTouchEvents from 'beautiful-react-hooks/useTouchEvents';
const MyComponent = () => {
@@ -79,10 +83,13 @@ const MyComponent = () => {
});
return (
-
- The current touch coordinates are:
- x:{coordinates[0]} y:{coordinates[1]}
-
+
+
+
+ Touch X: {coordinates[0]}
+ Touch Y: {coordinates[1]}
+
+
);
};
@@ -93,24 +100,58 @@ const MyComponent = () => {
#### β
When to use
-- When need to abstract touch related logics into custom hooks(s)
+- When you need to abstract touch-related logics into custom hooks(s)
#### π What not to do
-- You can't use the returned handler setter asynchronously, it will not have any result but changing the handler possibly leading to bugs in
- your code.
-- Absolutely avoid using `useTouchEvents` handler setters to replace the standard touch handler props.
-- `useTouchEvents` is meant to be used to abstract more complex hooks that need to control the mouse, for example: a drag n drop hook.
-- Using `useTouchEvents` handlers instead of the classic props approach it's just as bad as it sounds since you'll lose the React
- SyntheticEvent performance boost.
-- If you were doing something like the following, please keep doing it:
+- Do not use the returned callback setters asynchronously, as doing so will have no effect and may result in bugs in your code.
+- Avoid using `useTouchEvents` callback setters to replace standard mouse handler props.
+- `useTouchEvents` is designed to be used for abstracting more complex hooks that need to control the mouse, such as a drag-and-drop hook.
+- Using `useTouchEvents` handlers instead of the classic props approach will result in decreased performance due to the loss of the React
+ SyntheticEvent performance boost. If you were using a classic props approach before, continue to do so.
```jsx harmony static noedit
const MyComponent = (props) => {
- const { touchStartHandler } = props;
+ const { mouseDownHandler } = props;
return (
-
+
);
};
-```
+```
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+import { type CallbackSetter } from './shared/types';
+/**
+ * Returns a frozen object of callback setters to handle the touch events.
+ * It accepts a DOM ref representing the events target.
+ * If a target is not provided the events will be globally attached to the document object.
+ *
+ * ### Shall the `useTouchEvents` callbacks replace the standard mouse handler props?
+ *
+ * **They shall not!**
+ * **useTouchEvents is meant to be used to abstract more complex hooks that need to control mouse**, for instance:
+ * a drag n drop hook.
+ * Using useTouchEvents handlers instead of the classic props approach it's just as bad as it sounds since you'll
+ * lose the React SyntheticEvent performance boost.
+ * If you were doing something like the following:
+ *
+ */
+declare const useTouchEvents: (targetRef?: RefObject | undefined, passive?: boolean) => Readonly;
+/**
+ * The return object of the `useTouchEvents` hook.
+ */
+export interface UseTouchEventsReturn {
+ onTouchStart: CallbackSetter;
+ onTouchEnd: CallbackSetter;
+ onTouchCancel: CallbackSetter;
+ onTouchMove: CallbackSetter;
+}
+export default useTouchEvents;
+
+```
+
\ No newline at end of file
diff --git a/docs/useTouchState.md b/docs/useTouchState.md
index 0019cc51..333dc1cb 100644
--- a/docs/useTouchState.md
+++ b/docs/useTouchState.md
@@ -1,14 +1,14 @@
# useTouchState
-Returns the touch objects from the current touch events. It accepts a DOM ref representing the events target (where attach the events to).
-
-If a target is not provided the events will be globally attached to the `document` object.
+A hook that returns relevant properties from the last touch event, such as clientX and clientY. To ensure that events are attached to the
+intended target, please provide a DOM reference to the hook. If no target is specified, the events will be attached to the the `document`
+object globally.
### Why? π‘
-- allow to easily get the touch state
-- takes care of adding the mouse events listeners globally or to a defined target
-- takes care of cleaning the listener when the component unmounts
+- Allows to quickly get relevant information on the last touch event
+- Manages the addition of event listeners either globally or to a defined target
+- Ensures the listener is cleaned up when the component unmounts
### Basic Usage:
@@ -16,19 +16,29 @@ Provide a DOM ref as first parameter to `useTouchState`
```jsx harmony
import { useRef } from 'react';
+import { Tag, Space, Alert } from 'antd';
import useTouchState from 'beautiful-react-hooks/useTouchState';
const TouchReporter = () => {
const ref = useRef();
const touches = useTouchState(ref);
+ const lastTouch = touches[0];
return (
-
+
- Touch over me to get its current coordinates:
- {touches && touches[0] && (
-
x: {touches[0].clientX}, y: {touches[0].clientY}
- )}
+
+
+ {touches.length > 0 && lastTouch && (
+ <>
+ Touch X: {lastTouch.clientX}
+ Touch Y: {lastTouch.clientY}
+ >
+ )}
+ {touches.length === 0 && (
+
+ )}
+
);
@@ -39,30 +49,56 @@ const TouchReporter = () => {
### Global events
-Avoid providing any argument to `useTouchState`
+Attach the touch events globally by simply not providing any dom reference to the `useTouchState` hook
```jsx harmony
-import useTouchState from 'beautiful-react-hooks/useTouchState';
+import useTouchState from 'beautiful-react-hooks/useTouchState';
+import { Tag, Space, Alert } from 'antd';
const TouchReporter = () => {
const touches = useTouchState();
-
+ const lastTouch = touches[0];
+
return (
-
- The current touch coordinates are:
- {touches && touches[0] && (
- x: {touches[0].clientX}, y: {touches[0].clientY}
- )}
-
+
+
+
+ {touches.length > 0 && lastTouch && (
+ <>
+ Touch X: {lastTouch.clientX}
+ Touch Y: {lastTouch.clientY}
+ >
+ )}
+ {touches.length === 0 && (
+
+ )}
+
+
);
};
```
-
### Mastering the hook
#### β
When to use
-- If need to easily receive the mouse position
+- When you need to abstract touch-related logics into custom hooks(s)
+- When you need to quickly get the last touch position
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Returns the current touches from the touch move event.
+ * It possibly accepts a DOM ref representing the mouse target.
+ * If a target is not provided the state will be caught globally.
+ */
+declare const useTouchState: (targetRef?: RefObject | undefined) => TouchList;
+export default useTouchState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useURLSearchParams.md b/docs/useURLSearchParams.md
index 70b6f3b0..f8143b47 100644
--- a/docs/useURLSearchParams.md
+++ b/docs/useURLSearchParams.md
@@ -1,19 +1,20 @@
-# useQueryParams
+# useURLSearchParams
-Very similar to `useQueryParam` (mind the final 's'), it eases the process of manipulate a query string with multiple values.
+A hook that encapsulates the functionality of retrieving an always updated URLSearchParams object.
### Why? π‘
-- Ease the process of use an always updated instance of URLSearchParams
-- it's NOT built on top of version 6 of react-router-dom's useSearchParams, it is therefore compatible with older version
+- simplify the process of obtaining an always up-to-date instance of the URLSearchParams object
+- This hook is not based on the useSearchParams hook from version **6** of the `react-router-dom` library. Therefore, it is compatible with
+ earlier versions of `react-router-dom`
### Basic Usage:
```jsx harmony
import { useState, useRef } from 'react';
import { HashRouter as Router, useHistory } from 'react-router-dom'
-import { Button, Input } from 'beautiful-react-ui'
-import useURLSearchParams from 'beautiful-react-hooks/useURLSearchParams';
+import { Button, Input } from 'antd'
+import useURLSearchParams from 'beautiful-react-hooks/useURLSearchParams'
import useDidMount from 'beautiful-react-hooks/useDidMount'
const ExampleComponent = () => {
@@ -30,7 +31,7 @@ const ExampleComponent = () => {
})
return (
-
+
Current value of 'foo' param is '{params.get('foo')}'
Change the value of the foo param to see how this hook works
@@ -41,3 +42,16 @@ const ExampleComponent = () => {
```
+
+
+### Types
+
+```typescript static
+/**
+ * Wraps the business logic of retrieve always updated URLSearchParams
+ */
+declare const useURLSearchParams: () => URLSearchParams;
+export default useURLSearchParams;
+
+```
+
\ No newline at end of file
diff --git a/docs/useUpdateEffect.md b/docs/useUpdateEffect.md
index dd36dd85..e014d55e 100644
--- a/docs/useUpdateEffect.md
+++ b/docs/useUpdateEffect.md
@@ -1,17 +1,14 @@
# useUpdateEffect
--- This hook is a modification to `useEffect` hook that is skipping the first render --
-
-### π‘ Why?
-
-- Sometimes you do not want to run useEffect on the first render and this hook allows you to do this
+A hook that modifies the behavior of the `useEffect` hook by skipping the initial render. This hook is particularly useful in cases where
+the effect should only run after the first update of the component, but not during the initial mount.
### Basic Usage:
```jsx harmony
import { useState, useEffect, useCallback } from 'react';
-import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
-import useUpdateEffect from 'beautiful-react-hooks/useUpdateEffect';
+import { Alert, Space, Button } from 'antd';
+import useUpdateEffect from 'beautiful-react-hooks/useUpdateEffect';
const UseUpdateEffectExample = () => {
const [data, setData] = useState(0)
@@ -27,12 +24,13 @@ const UseUpdateEffectExample = () => {
const setNewDate = useCallback(() => setData(Date.now()), []);
return (
-
- Open a console to see result and try to click update date button
-
-
- Update data
-
+
+
+
+
+ Update data
+
+
);
};
@@ -40,8 +38,18 @@ const UseUpdateEffectExample = () => {
```
-### Mastering the hooks
+
+### Types
+
+```typescript static
+import { type DependencyList, type EffectCallback } from 'react';
+/**
+ * A hook that runs an effect after the first render.
+ * @param callback
+ * @param deps
+ */
+declare const useUpdateEffect: (callback: EffectCallback, deps?: DependencyList) => void;
+export default useUpdateEffect;
-#### β
When to use
-
-- When you want to skip first render of useEffect
+```
+
\ No newline at end of file
diff --git a/docs/useValidatedState.md b/docs/useValidatedState.md
index 7327244e..20385a60 100644
--- a/docs/useValidatedState.md
+++ b/docs/useValidatedState.md
@@ -10,7 +10,7 @@ state array where the third parameter is result of the validation.
### Basic Usage:
```jsx harmony
-import { Input } from 'beautiful-react-ui';
+import { Input, Space, Typography } from 'antd';
import useValidatedState from 'beautiful-react-hooks/useValidatedState';
const passwordValidator = (password) => password.length > 3;
@@ -19,16 +19,18 @@ const ValidatedField = () => {
const [password, setPassword, validation] = useValidatedState(passwordValidator, 'sk8');
return (
-
- setPassword(e.target.value)}
- color={validation.valid ? 'success' : 'danger'}
- icon="key"
- placeholder="Insert password"
- helpText={validation.valid ? 'Password is valid' : 'Password is too short'}
- fluid
- />
+
+
+ setPassword(e.target.value)}
+ status={!validation.valid && 'error'}
+ placeholder="Insert password"
+ />
+
+ {validation.valid ? 'Password is valid' : 'Password is too short'}
+
+
);
};
@@ -41,3 +43,21 @@ const ValidatedField = () => {
#### β
good to know:
- useValidatedState does not re-render your component twice to save the validation state.
+
+
+### Types
+
+```typescript static
+/**
+ * Returns a state that changes only if the next value pass its validator
+ */
+declare const useValidatedState: >(validator: TValidator, initialValue?: TValue | undefined) => [TValue, (nextValue: TValue) => void, ValidationResult];
+export type Validator = (value: TValue) => boolean;
+export interface ValidationResult {
+ changed: boolean;
+ valid?: boolean;
+}
+export default useValidatedState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useValueHistory.md b/docs/useValueHistory.md
index fd0ad953..eceed668 100644
--- a/docs/useValueHistory.md
+++ b/docs/useValueHistory.md
@@ -1,15 +1,16 @@
# useValueHistory
-Accepts a variable (*possibly a prop or a state*) and returns its history (changes through updates).
+A hook that takes a variable, which can be a prop or a state, and returns an array of its previous values. This hook is useful for tracking
+changes in a variable across multiple renders and allows developers to compare the current value with its previous values.
-### Why? π‘
-
-- You want to keep track of the history of a value
+Overall, the "usePrevious" hook is a helpful tool for debugging and improving the performance of React components that rely on the history
+of a specific variable
### Basic Usage:
```jsx harmony
import { useState } from 'react';
+import { Tag, Typography } from 'antd';
import useValueHistory from 'beautiful-react-hooks/useValueHistory';
import useInterval from 'beautiful-react-hooks/useInterval';
@@ -20,15 +21,28 @@ const TestComponent = () => {
useInterval(() => setCount(1 + count), 500);
return (
-
- Count: {count}
- The history of the `count` state is:
-
+
+ Count: {count}
+ The history of the `count` state is:
+
{countHistory.join(', ')}
-
+
);
};
```
+
+
+### Types
+
+```typescript static
+/**
+ * Accepts a variable (possibly a prop or a state) and returns its history (changes through updates).
+ */
+declare const useValueHistory: (value: TValue, distinct?: boolean) => TValue[];
+export default useValueHistory;
+
+```
+
\ No newline at end of file
diff --git a/docs/useViewportSpy.md b/docs/useViewportSpy.md
index 07c7ab16..7340cdba 100644
--- a/docs/useViewportSpy.md
+++ b/docs/useViewportSpy.md
@@ -1,17 +1,18 @@
# useViewportSpy
-Uses the [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) API to tell whether the given DOM
-Element (from useRef) is visible within the viewport.
+A hook that uses the [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) API to tell whether the
+provided DOM Element is visible within the viewport.
### Why? π‘
- Asynchronously observes changes in the intersection of the given element with the document
-- Can be used to perform animation when the component appear within the viewport
+- Can be used to perform animation when the component appear into the viewport
### Basic Usage:
```jsx harmony
import { useRef } from 'react';
+import { Space, Typography, Tag } from 'antd';
import useViewportSpy from 'beautiful-react-hooks/useViewportSpy';
const ViewportSpyComponent = () => {
@@ -20,12 +21,15 @@ const ViewportSpyComponent = () => {
return (
-
- Observed element
-
-
- is the observed element in viewport? {isVisible ? 'yes' : 'no'}
-
+
+
+ Observed element
+
+
+ is the observed element in viewport?
+ {isVisible ? 'yes' : 'no'}
+
+
);
};
@@ -35,11 +39,12 @@ const ViewportSpyComponent = () => {
### Options
-The second argument could possibly be an object
-of [IntersectionObserver options](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver)
+Pass [IntersectionObserver options](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver) as second
+parameter to customize the behavior of the hook
```jsx harmony
import { useRef } from 'react';
+import { Space, Typography, Tag } from 'antd';
import useViewportSpy from 'beautiful-react-hooks/useViewportSpy';
const ViewportSpyComponent = () => {
@@ -48,12 +53,15 @@ const ViewportSpyComponent = () => {
return (
-
- Observed element
-
-
- is the observed element in viewport? {isVisible ? 'yes' : 'no'}
-
+
+
+ Observed element
+
+
+ is the observed element in viewport?
+ {isVisible ? 'yes' : 'no'}
+
+
);
};
@@ -66,3 +74,18 @@ const ViewportSpyComponent = () => {
This hook can be used to perform animations when a component/element enters or exit the viewport. To deeply
understand [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver)
please read [Using the Intersection Observer API to Trigger Animations and Transitions](https://alligator.io/js/intersection-observer)
+
+
+### Types
+
+```typescript static
+import { type RefObject } from 'react';
+/**
+ * Uses the IntersectionObserverMock API to tell whether the given DOM Element (from useRef) is visible within the
+ * viewport.
+ */
+declare const useViewportSpy: (ref: RefObject, options?: IntersectionObserverInit) => boolean | undefined;
+export default useViewportSpy;
+
+```
+
\ No newline at end of file
diff --git a/docs/useViewportState.md b/docs/useViewportState.md
index cba817f9..998b2373 100644
--- a/docs/useViewportState.md
+++ b/docs/useViewportState.md
@@ -1,6 +1,6 @@
# useViewportState
-Returns information on the current viewport state
+A hook that returns relevant information on the current viewport state.
It's built on top of [useWindowResize](./useWindowResize.md) and [useWindowScroll](./useWindowScroll.md).
@@ -13,17 +13,19 @@ It's built on top of [useWindowResize](./useWindowResize.md) and [useWindowScrol
```jsx harmony
import { useState } from 'react';
+import { Typography, Tag } from 'antd';
import useViewportState from 'beautiful-react-hooks/useViewportState';
const WindowSizeReporter = () => {
const { width, height, scrollX, scrollY } = useViewportState();
return (
-
- window width: {width}
- window height: {height}
- window scrollX: {scrollX}
- window scrollY: {scrollY}
+
+ Window current properties
+ width: {width}
+ height: {height}
+ horizontal scroll: {scrollX}
+ vertical scroll: {scrollY}
);
};
@@ -36,3 +38,22 @@ const WindowSizeReporter = () => {
#### β
When to use
- When in need of reading common information about the current viewport
+
+
+### Types
+
+```typescript static
+export interface ViewportState {
+ width: number;
+ height: number;
+ scrollX: number;
+ scrollY: number;
+}
+/**
+ * Returns updated information on the current viewport state
+ */
+declare const useViewportState: (debounceBy?: number) => ViewportState;
+export default useViewportState;
+
+```
+
\ No newline at end of file
diff --git a/docs/useWillUnmount.md b/docs/useWillUnmount.md
index e00447f8..2084f14c 100644
--- a/docs/useWillUnmount.md
+++ b/docs/useWillUnmount.md
@@ -1,15 +1,15 @@
# useWillUnmount
-Accepts a function to be performed right before the component unmounts.
+A hook that takes in a function to execute right before the component unmounts.
### Why? π‘
-- takes care of performing a callback right before the component unmounts
-- It's as a shortcut to `useEffect(() => () => willUnmount, [])`;
+- takes care of performing a callback when the component unmounts
### Basic Usage:
```jsx harmony
+import { Typography } from 'antd';
import useWillUnmount from 'beautiful-react-hooks/useWillUnmount';
const ComponentWillUnmount = () => {
@@ -18,8 +18,8 @@ const ComponentWillUnmount = () => {
});
return (
-
- Check the javascript console after moving from this page
+
+ Check the javascript console after moving from this page
);
};
@@ -29,13 +29,14 @@ const ComponentWillUnmount = () => {
### Callback setter syntax:
-if the first parameter is not provided, the returned function (*a handler setter*) can be used to set the `useWillUnmount` handler, as long
-as it is immediately invoked.
+If the first parameter is omitted, you can use the returned function (a callback setter) to set the useWillUnmount handler. However, you
+must immediately invoke the callback setter.
-**Please note**: the returned handler setter is meant to change the value of the callback reference only, it does not cause the component
-rerender nor should not be invoked asynchronously.
+Important: The callback setter only changes the value of the callback reference and does not trigger a component rerender. Also, avoid
+invoking it asynchronously
```jsx harmony
+import { Typography } from 'antd';
import useWillUnmount from 'beautiful-react-hooks/useWillUnmount';
const ComponentWillUnmount = () => {
@@ -46,8 +47,8 @@ const ComponentWillUnmount = () => {
});
return (
-
- Check the javascript console after moving from this page
+
+ Check the javascript console after moving from this page
);
};
@@ -69,9 +70,23 @@ by [Dan Abramov](https://twitter.com/dan_abramov)
#### β
When to use
-- When in need of performing a function after the component did mount
+- When you need to perform a function after the component has mounted
#### π When not to use
-- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
-- If using the handler setter, it should not be used asynchronously but immediately invoked
+- Avoid using this hook asynchronously since it would violate the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+- If you're using the callback setter, make sure to invoke it immediately instead of asynchronously
+
+
+### Types
+
+```typescript static
+import { type GenericFunction } from './shared/types';
+/**
+ * Returns a callback setter for a callback to be performed when the component will unmount.
+ */
+declare const useWillUnmount: (callback?: TCallback | undefined) => import("./shared/types").CallbackSetter;
+export default useWillUnmount;
+
+```
+
\ No newline at end of file
diff --git a/docs/useWindowResize.md b/docs/useWindowResize.md
index 57a3e76c..1a3e4b06 100644
--- a/docs/useWindowResize.md
+++ b/docs/useWindowResize.md
@@ -1,18 +1,19 @@
# useWindowResize
-Accepts a function to be performed during the window resize event.
+A hook that receives a callback function to execute on the window's resize event.
It's built on top of [useGlobalEvent](./useGlobalEvent.md).
### Why? π‘
-- takes care of adding the listener for the window resize event.
-- takes care of removing the listener when the component will unmount
+- Simplifies the process of adding a listener for a specific event to the `window` object.
+- Automates the removal of the listener when the component is unmounted.
### Basic Usage:
```jsx harmony
import { useState } from 'react';
+import { Typography, Tag } from 'antd';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
const WindowSizeReporter = () => {
@@ -25,9 +26,13 @@ const WindowSizeReporter = () => {
});
return (
-
- window width: {width}
- window height: {height}
+
+
+ current window width: {width}
+
+
+ current window height: {height}
+
);
};
@@ -37,14 +42,15 @@ const WindowSizeReporter = () => {
### Callback setter syntax:
-if the first parameter is not provided, the returned function (*a handler setter*) can be used to set the `useWindowResize` handler, as long
-as it is immediately invoked.
+if the first parameter is not provided, the returned function (*a callback setter*) can be used to set the `useWindowResize` handler, as
+long as it is immediately invoked.
-**Please note**: the returned handler setter is meant to change the value of the callback reference only, it does not cause the component
+**Please note**: the returned callback setter is meant to change the value of the callback reference only, it does not cause the component
rerender nor should not be invoked asynchronously.
```jsx harmony
import { useState } from 'react';
+import { Typography, Tag } from 'antd';
import useWindowResize from 'beautiful-react-hooks/useWindowResize';
const WindowSizeReporter = () => {
@@ -58,9 +64,13 @@ const WindowSizeReporter = () => {
});
return (
-
- window width: {width}
- window height: {height}
+
+
+ current window width: {width}
+
+
+ current window height: {height}
+
);
};
@@ -76,7 +86,9 @@ preventing too many useless renders, please take into account using
```jsx harmony
import { useState } from 'react';
-import { useWindowResize, useThrottledCallback } from 'beautiful-react-hooks';
+import { Typography, Tag } from 'antd';
+import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback';
+import useWindowResize from 'beautiful-react-hooks/useWindowResize';
const WindowSizeReporter = () => {
const [width, setWidth] = useState(window.innerWidth);
@@ -89,9 +101,13 @@ const WindowSizeReporter = () => {
}));
return (
-
- window width: {width}
- window height: {height}
+
+
+ current window width: {width}
+
+
+ current window height: {height}
+
);
};
@@ -107,5 +123,18 @@ const WindowSizeReporter = () => {
#### π When not to use
-- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
-- If using the handler setter, it should not be used asynchronously but immediately invoked
+- Avoid using this hook asynchronously since it would violate the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+- If you're using the callback setter, make sure to invoke it immediately instead of asynchronously
+
+
+### Types
+
+```typescript static
+/**
+ * Returns a function that accepts a callback to be performed when the window resize.
+ */
+declare const useWindowResize: () => import("./shared/types").CallbackSetter;
+export default useWindowResize;
+
+```
+
\ No newline at end of file
diff --git a/docs/useWindowScroll.md b/docs/useWindowScroll.md
index 041237c9..35651597 100644
--- a/docs/useWindowScroll.md
+++ b/docs/useWindowScroll.md
@@ -1,18 +1,19 @@
# useWindowScroll
-Accepts a function to be performed during the window scroll event.
+A hook that receives a callback function to execute on the window's scroll event.
It's built on top of [useGlobalEvent](./useGlobalEvent.md).
### Why? π‘
-- takes care of adding the listener for the window scroll event.
-- takes care of removing the listener when the component will unmount
+- Simplifies the process of adding a listener for a specific event to the `window` object.
+- Automates the removal of the listener when the component is unmounted.
### Basic usage:
```jsx harmony
import { useState } from 'react';
+import { Typography, Tag } from 'antd';
import useWindowScroll from 'beautiful-react-hooks/useWindowScroll';
const WindowScrollReporter = () => {
@@ -25,7 +26,9 @@ const WindowScrollReporter = () => {
return (
- window y-scroll: {scrollY}
+
+ current window vertical scroll: {scrollY}
+
);
};
@@ -35,14 +38,15 @@ const WindowScrollReporter = () => {
### Callback setter syntax:
-if the first parameter is not provided, the returned function (*a handler setter*) can be used to set the `useWindowScroll` handler, as long
-as it is immediately invoked.
+if the first parameter is not provided, the returned function (*a callback setter*) can be used to set the `useWindowScroll` handler, as
+long as it is immediately invoked.
-**Please note**: the returned handler setter is meant to change the value of the callback reference only, it does not cause the component
+**Please note**: the returned callback setter is meant to change the value of the callback reference only, it does not cause the component
rerender nor should not be invoked asynchronously.
```jsx harmony
import { useState } from 'react';
+import { Typography, Tag } from 'antd';
import useWindowScroll from 'beautiful-react-hooks/useWindowScroll';
const WindowScrollReporter = () => {
@@ -55,7 +59,9 @@ const WindowScrollReporter = () => {
return (
- window y-scroll: {scrollY}
+
+ current window vertical scroll: {scrollY}
+
);
};
@@ -71,7 +77,9 @@ preventing too many useless renders, please take into account using
```jsx harmony
import { useState } from 'react';
-import { useWindowScroll, useThrottledCallback } from 'beautiful-react-hooks';
+import { Typography, Tag } from 'antd';
+import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback'
+import useWindowScroll from 'beautiful-react-hooks/useWindowScroll';
const WindowScrollReporter = () => {
const [scrollY, setScrollY] = useState(window.scrollY);
@@ -83,7 +91,9 @@ const WindowScrollReporter = () => {
return (
- window y-scroll: {scrollY}
+
+ current window vertical scroll: {scrollY}
+
);
};
@@ -99,5 +109,18 @@ const WindowScrollReporter = () => {
#### π When not to use
-- You can't use it asynchronously since this will break the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
-- If using the handler setter, it should not be used asynchronously but immediately invoked
+- Avoid using this hook asynchronously since it would violate the [rules of hooks](https://reactjs.org/docs/hooks-rules.html)
+- If you're using the callback setter, make sure to invoke it immediately instead of asynchronously
+
+
+### Types
+
+```typescript static
+/**
+ * Returns a function that accepts a callback to be performed when the window scrolls.
+ */
+declare const useWindowScroll: () => import("./shared/types").CallbackSetter;
+export default useWindowScroll;
+
+```
+
\ No newline at end of file
diff --git a/docs/utils/_custom.css b/docs/utils/_custom.css
index 8519eff9..01602667 100644
--- a/docs/utils/_custom.css
+++ b/docs/utils/_custom.css
@@ -1,6 +1,6 @@
@import url('https://fonts.googleapis.com/css?family=Ubuntu:300,300i,400,400i,500,500i,700,700i&display=swap');
-@import "~beautiful-react-ui/beautiful-react-ui.css";
+@import '~antd/dist/reset.css';
body {
- font-family: 'Ubuntu', sans-serif;
+ font-family: 'Ubuntu', sans-serif;
}
diff --git a/docs/utils/_setup.js b/docs/utils/_setup.js
index 1360ca46..13896243 100644
--- a/docs/utils/_setup.js
+++ b/docs/utils/_setup.js
@@ -1,14 +1,6 @@
-const React = require('react');
+const React = require('react')
+const { Card } = require('antd')
-const defaultStyle = {
- background: '#FDFEFD',
- width: '250px',
- padding: '20px',
- textAlign: 'center',
- boxShadow: '0 0 10px rgba(20, 20, 20, .1)',
- margin: '10px auto',
-};
-
-const DisplayDemo = window.DisplayDemo = ({ style, ...props }) => (
- React.createElement('div', { style: { ...defaultStyle, ...style } }, props.children)
-);
+const DisplayDemo = window.DisplayDemo = (props) => (
+ React.createElement(Card, { bordered: true, hoverable: true, ...props }, props.children)
+)
diff --git a/docs/utils/_styleguidist.theme.js b/docs/utils/_styleguidist.theme.js
index f0897d5e..3bab7bc7 100644
--- a/docs/utils/_styleguidist.theme.js
+++ b/docs/utils/_styleguidist.theme.js
@@ -2,19 +2,16 @@ module.exports = {
// https://github.com/styleguidist/react-styleguidist/blob/master/src/client/styles/theme.ts
theme: {
color: {
- base: '#606f7b',
- text: '#606f7b',
+ base: '#2D3142',
+ text: '#2D3142',
link: '#1D6C8B',
linkHover: '#317995'
},
- baseColor: '#606f7b',
+ baseColor: '#2D3142',
fontFamily: {
base: '"Ubuntu", "sans-serif", light',
},
},
- template: {
- favicon: 'https://beautifulinteractions.com/favicons/bi-favicon.ico',
- },
styles: {
SectionHeading: {
wrapper: {
@@ -54,11 +51,12 @@ module.exports = {
},
Playground: {
preview: {
- border: '2px solid rgba(0, 0, 0, .05)',
- background: 'white',
- borderRadius: '5px',
- boxShadow: '0 0px 10px 0 rgba(93, 100, 148, 0.05)',
+ padding: 0,
+ border: 'none',
+ background: 'transparent',
+ //borderRadius: '6px',
+ // boxShadow: '0 0px 10px 0 rgba(93, 100, 148, 0.05)',
},
},
},
-};
+}
diff --git a/package.json b/package.json
index ad9ed560..a8eaba65 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"build-cjs": "tsc --project ./tsconfig.cjs.json",
"build-esm": "tsc --project ./tsconfig.esm.json",
"build": "npx del-cli dist && npm run build-cjs && npm run build-esm && npm run build-types && echo 'Successfully built'",
- "build-doc": "npx del-cli dist-ghpages && npx styleguidist build",
+ "build-doc": "npx del-cli dist-ghpages && node scripts/generate-doc-append-types.js && npx styleguidist build",
"test": "nyc mocha --recursive --exit \"./test/**/*.spec.+(js|jsx)\"",
"test:watch": "npm run test -- --watch",
"start": "npx styleguidist server",
@@ -44,67 +44,62 @@
"lodash.throttle": "^4.1.1"
},
"peerDependencies": {
- "react": ">=16.0.0",
- "react-dom": ">=16.0.0",
- "react-router-dom": ">=5.0.0",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "react-router-dom": ">=5.0.0 <=6.0.0",
"rxjs": ">=7.0.0"
},
"devDependencies": {
- "@babel/core": "7.18.2",
- "@babel/polyfill": "^7.10.4",
- "@babel/preset-env": "7.18.2",
- "@babel/preset-react": "7.17.12",
- "@babel/register": "^7.17.7",
- "@semantic-release/changelog": "6.0.1",
+ "@ant-design/icons": "5.0.1",
+ "@babel/core": "7.21.0",
+ "@babel/preset-env": "7.20.2",
+ "@babel/preset-react": "7.18.6",
+ "@babel/register": "^7.21.0",
+ "@semantic-release/changelog": "6.0.2",
"@semantic-release/commit-analyzer": "9.0.2",
"@semantic-release/exec": "6.0.3",
"@semantic-release/git": "10.0.1",
- "@semantic-release/github": "8.0.4",
- "@semantic-release/npm": "9.0.1",
- "@testing-library/react": "13.3.0",
- "@testing-library/react-hooks": "8.0.1",
+ "@semantic-release/github": "8.0.7",
+ "@semantic-release/npm": "9.0.2",
+ "@testing-library/react": "14.0.0",
+ "@testing-library/react-hooks": "6.0.0",
"@types/lodash.debounce": "4.0.7",
"@types/lodash.throttle": "4.1.7",
"@types/react-router-dom": "5.3.3",
- "@typescript-eslint/eslint-plugin": "5.27.1",
- "@typescript-eslint/parser": "5.27.1",
- "babel-eslint": "^10.1.0",
- "babel-loader": "^8.2.5",
+ "antd": "5.3.1",
+ "babel-loader": "^9.1.2",
"babel-plugin-istanbul": "^6.1.1",
"babel-plugin-transform-require-ignore": "^0.1.1",
- "beautiful-react-ui": "0.57.1",
- "chai": "^4.3.6",
- "css-loader": "^6.7.1",
- "eslint": "8.21.0",
- "eslint-config-airbnb-base": "4.0.2",
- "eslint-config-airbnb-typescript": "16.1.1",
- "eslint-plugin-chai-expect": "^3.0.0",
- "eslint-plugin-import": "1.11.0",
- "eslint-plugin-jsx-a11y": "6.6.1",
- "eslint-plugin-react": "7.30.1",
- "eslint-plugin-react-hooks": "4.5.0",
- "glob": "^8.0.3",
- "husky": "^8.0.1",
- "jsdoc-to-markdown": "^7.1.1",
- "jsdom": "^19.0.0",
+ "chai": "^4.3.7",
+ "css-loader": "^6.7.3",
+ "eslint": "8.36.0",
+ "eslint-config-standard-with-typescript": "34.0.0",
+ "eslint-plugin-import": "2.27.5",
+ "eslint-plugin-n": "15.6.1",
+ "eslint-plugin-promise": "6.1.1",
+ "eslint-plugin-react": "7.32.2",
+ "glob": "^9.2.1",
+ "husky": "^8.0.3",
+ "jsdoc-to-markdown": "^8.0.0",
+ "jsdom": "^21.1.1",
"jsdom-global": "^3.0.2",
- "mocha": "10.0.0",
+ "mocha": "10.2.0",
"mock-local-storage": "1.1.23",
"mutation-observer": "1.0.3",
"nyc": "^15.1.0",
- "react": "18.1.0",
- "react-dom": "18.1.0",
- "react-router-dom": "5.3.3",
- "react-styleguidist": "13.0.0",
- "regenerator-runtime": "0.13.9",
- "rxjs": "7.5.5",
- "semantic-release": "^19.0.3",
- "sinon": "^14.0.0",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "react-router-dom": "5.3.4",
+ "react-styleguidist": "13.1.1",
+ "regenerator-runtime": "0.13.11",
+ "rxjs": "7.8.0",
+ "semantic-release": "^20.1.1",
+ "sinon": "^15.0.2",
"style-loader": "^3.3.1",
- "ts-loader": "9.3.0",
- "typescript": "4.7.3",
+ "ts-loader": "9.4.2",
+ "typescript": "4.9.5",
"url-loader": "^4.1.1",
- "webpack": "5.74.0"
+ "webpack": "5.76.1"
},
"exports": {
".": {
@@ -340,4 +335,4 @@
"require": "./useWindowScroll.js"
}
}
-}
\ No newline at end of file
+}
diff --git a/scripts/generate-doc-append-types.js b/scripts/generate-doc-append-types.js
new file mode 100644
index 00000000..08af1adb
--- /dev/null
+++ b/scripts/generate-doc-append-types.js
@@ -0,0 +1,44 @@
+const fs = require('fs/promises')
+const path = require('path')
+const { globSync } = require('glob')
+
+const docsPath = path.join(__dirname, '..', 'docs')
+const distPath = path.join(__dirname, '..', 'dist')
+const docFiles = globSync(`${docsPath}/*.md`)
+ .map((file) => file.replace(`${docsPath}/`, '').replace('.md', ''))
+ .filter((file) => file.startsWith('use'))
+
+docFiles.forEach(async (hook) => {
+ const docPath = path.join(docsPath, `${hook}.md`)
+ const typeFile = path.join(distPath, `${hook}.d.ts`)
+
+ const declarations = await fs.readFile(typeFile, { encoding: 'utf8' })
+ const document = await fs.readFile(docPath, { encoding: 'utf8' })
+
+ if (document.match(//g)) {
+ const cleared = emptyOldTypes(document).trim()
+ const nextDocument = cleared.replace('', template(declarations)).trim()
+
+ fs.writeFile(docPath, nextDocument, { encoding: 'utf8' }).then(() => {
+ console.log(`Updated "${hook}" types`)
+ })
+ }
+})
+
+const template = (content) => `
+### Types
+
+\`\`\`typescript static
+${content}
+\`\`\`
+
+`
+
+const emptyOldTypes = (content) => {
+ const regex = /[\s\S]*/g
+
+ return `${content.replace(regex, '\n').replace(//g, '').trim()}
+
+
+`
+}
diff --git a/scripts/generate-exports.js b/scripts/generate-exports.js
index 2a4fb696..bfef671c 100644
--- a/scripts/generate-exports.js
+++ b/scripts/generate-exports.js
@@ -2,14 +2,14 @@
const fs = require('fs')
const path = require('path')
-const glob = require('glob')
+const { globSync } = require('glob')
const srcPath = path.join(__dirname, '..', 'src')
const pkgPath = path.join(__dirname, '..', 'package.json')
-const srcFiles = glob.sync(`${srcPath}/*.ts`)
- .map((file) => file.replace(`${srcPath}/`, '').replace('.ts', ''))
- .filter((file) => file !== 'index')
+const srcFiles = globSync(`${srcPath}/*.ts`)
+ .map((file) => file.replace(`${srcPath}/`, '').replace('.ts', ''))
+ .filter((file) => file !== 'index')
const defaultExports = {
'.': {
@@ -22,7 +22,7 @@ const exportsObj = srcFiles.reduce((acc, file) => ({
...acc,
[`./${file}`]: {
import: `./esm/${file}.js`,
- require: `./${file}.js`,
+ require: `./${file}.js`
}
}), defaultExports)
diff --git a/src/factory/createHandlerSetter.ts b/src/factory/createHandlerSetter.ts
index 15f70b91..5cb1a5cb 100644
--- a/src/factory/createHandlerSetter.ts
+++ b/src/factory/createHandlerSetter.ts
@@ -1,5 +1,5 @@
-import { RefObject, useRef } from 'react'
-import { CallbackSetter, SomeCallback } from '../shared/types'
+import { type RefObject, useRef } from 'react'
+import { type CallbackSetter, type SomeCallback } from '../shared/types'
/**
* Returns an array where the first item is the [ref](https://reactjs.org/docs/hooks-reference.html#useref) to a
diff --git a/src/factory/createStorageHook.ts b/src/factory/createStorageHook.ts
index b12c9957..842cbc38 100644
--- a/src/factory/createStorageHook.ts
+++ b/src/factory/createStorageHook.ts
@@ -7,7 +7,7 @@ import noop from '../shared/noop'
import warnOnce from '../shared/warnOnce'
/**
- * An utility to quickly create hooks to access both Session Storage and Local Storage
+ * A utility to quickly create hooks to access both Session Storage and Local Storage
*/
const createStorageHook = (type: 'session' | 'local') => {
type SetValue = (value: TValue | ((previousValue: TValue) => TValue)) => void
@@ -20,10 +20,7 @@ const createStorageHook = (type: 'session' | 'local') => {
/**
* the hook
*/
- return function useStorageCreatedHook(
- storageKey: string,
- defaultValue?: any,
- ): [TValue, SetValue] {
+ return function useStorageCreatedHook (storageKey: string, defaultValue?: any): [TValue | null, SetValue] {
if (!isClient) {
if (isDevelopment) {
warnOnce(`Please be aware that ${storageName} could not be available during SSR`)
@@ -40,18 +37,18 @@ const createStorageHook = (type: 'session' | 'local') => {
}
}, [storage, storageKey])
- const [storedValue, setStoredValue] = useState(
+ const [storedValue, setStoredValue] = useState(
() => {
let valueToStore: string
try {
- valueToStore = storage.getItem(storageKey) || JSON.stringify(defaultValue)
+ valueToStore = storage.getItem(storageKey) ?? JSON.stringify(defaultValue)
} catch (e) {
valueToStore = JSON.stringify(defaultValue)
}
safelySetStorage(valueToStore)
return safelyParseJson(valueToStore)
- },
+ }
)
const setValue: SetValue = useCallback(
diff --git a/src/index.ts b/src/index.ts
deleted file mode 100644
index 4c36911b..00000000
--- a/src/index.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * This file is kept for compatibility reasons.
- * You should avoid importing hooks directly from this file.
- *
- * Avoid importing hooks like this:
- *
- * ```js
- * import { useSomething } from 'beautiful-react-hooks';
- * ```
- *
- * in favour of this:
- *
- * ```js
- * import useSomething from 'beautiful-react-hooks/useSomething';
- * ```
- */
-export { default as useDidMount } from './useDidMount'
-export { default as useWillUnmount } from './useWillUnmount'
-export { default as useLifecycle } from './useLifecycle'
-export { default as useWindowResize } from './useWindowResize'
-export { default as useWindowScroll } from './useWindowScroll'
-export { default as useDebouncedCallback } from './useDebouncedCallback'
-export { default as useThrottledCallback } from './useThrottledCallback'
-export { default as useMouse } from './useMouse'
-export { default as useMouseEvents } from './useMouseEvents'
-export { default as useMouseState } from './useMouseState'
-export { default as useTimeout } from './useTimeout'
-export { default as useInterval } from './useInterval'
-export { default as useGlobalEvent } from './useGlobalEvent'
-export { default as usePreviousValue } from './usePreviousValue'
-export { default as useGeolocation } from './useGeolocation'
-export { default as useGeolocationEvents } from './useGeolocationEvents'
-export { default as useGeolocationState } from './useGeolocationState'
-export { default as useMediaQuery } from './useMediaQuery'
-export { default as useValueHistory } from './useValueHistory'
-export { default as useOnlineState } from './useOnlineState'
-export { default as useViewportSpy } from './useViewportSpy'
-export { default as useValidatedState } from './useValidatedState'
-export { default as useDragEvents } from './useDragEvents'
-export { default as useDrag } from './useDrag'
-export { default as useDropZone } from './useDropZone'
-export { default as useRequestAnimationFrame } from './useRequestAnimationFrame'
-export { default as useLocalStorage } from './useLocalStorage'
-export { default as useSessionStorage } from './useSessionStorage'
-export { default as useResizeObserver } from './useResizeObserver'
-export { default as useDefaultedState } from './useDefaultedState'
-export { default as useObservable } from './useObservable'
-export { default as useSpeechSynthesis } from './useSpeechSynthesis'
-export { default as useSystemVoices } from './useSystemVoices'
-export { default as useRenderInfo } from './useRenderInfo'
-export { default as useSwipe } from './useSwipe'
-export { default as useHorizontalSwipe } from './useHorizontalSwipe'
-export { default as useVerticalSwipe } from './useVerticalSwipe'
-export { default as useSwipeEvents } from './useSwipeEvents'
-export { default as useConditionalTimeout } from './useConditionalTimeout'
-export { default as useInfiniteScroll } from './useInfiniteScroll'
-export { default as useQueryParam } from './useQueryParam'
-export { default as useQueryParams } from './useQueryParams'
-export { default as useSearchQuery } from './useSearchQuery'
-export { default as useEvent } from './useEvent'
-export { default as useViewportState } from './useViewportState'
-export { default as useToggle } from './useToggle'
-
-// keep it just for compatibility issues
-export { default as useStorage } from './factory/createStorageHook'
diff --git a/src/shared/geolocationUtils.ts b/src/shared/geolocationUtils.ts
index d770b449..b58f3bff 100644
--- a/src/shared/geolocationUtils.ts
+++ b/src/shared/geolocationUtils.ts
@@ -1,9 +1,9 @@
-import { BRHGeolocationPosition } from './types'
+import { type BRHGeolocationPosition } from './types'
export const geoStandardOptions: PositionOptions = Object.freeze({
enableHighAccuracy: false,
timeout: 0xFFFFFFFF,
- maximumAge: 0,
+ maximumAge: 0
})
/**
@@ -14,28 +14,30 @@ export const isSamePosition = (current: BRHGeolocationPosition, next: BRHGeoloca
if (current.timestamp && next.timestamp && current.timestamp !== next.timestamp) return false
return (
- (current.coords.latitude === next.coords.latitude)
- && (current.coords.longitude === next.coords.longitude)
- && (current.coords.altitude === next.coords.altitude)
- && (current.coords.accuracy === next.coords.accuracy)
- && (current.coords.altitudeAccuracy === next.coords.altitudeAccuracy)
- && (current.coords.heading === next.coords.heading)
- && (current.coords.speed === next.coords.speed)
+ (current.coords.latitude === next.coords.latitude) &&
+ (current.coords.longitude === next.coords.longitude) &&
+ (current.coords.altitude === next.coords.altitude) &&
+ (current.coords.accuracy === next.coords.accuracy) &&
+ (current.coords.altitudeAccuracy === next.coords.altitudeAccuracy) &&
+ (current.coords.heading === next.coords.heading) &&
+ (current.coords.speed === next.coords.speed)
)
}
/**
* Given a position object returns only its properties
*/
-export const makePositionObj = (position: BRHGeolocationPosition): BRHGeolocationPosition | null => (!position ? null : ({
- timestamp: position.timestamp,
- coords: {
- latitude: position.coords.latitude,
- longitude: position.coords.longitude,
- altitude: position.coords.altitude,
- accuracy: position.coords.accuracy,
- altitudeAccuracy: position.coords.altitudeAccuracy,
- heading: position.coords.heading,
- speed: position.coords.speed,
- },
-}))
+export const makePositionObj = (position: BRHGeolocationPosition) => (!position
+ ? null
+ : ({
+ timestamp: position.timestamp,
+ coords: {
+ latitude: position.coords.latitude,
+ longitude: position.coords.longitude,
+ altitude: position.coords.altitude,
+ accuracy: position.coords.accuracy,
+ altitudeAccuracy: position.coords.altitudeAccuracy,
+ heading: position.coords.heading,
+ speed: position.coords.speed
+ }
+ }))
diff --git a/src/shared/isFunction.ts b/src/shared/isFunction.ts
index 751cb3b8..3f83e4d7 100644
--- a/src/shared/isFunction.ts
+++ b/src/shared/isFunction.ts
@@ -1,8 +1,10 @@
-const isFunction = (functionToCheck: unknown): functionToCheck is Function => !!(
- typeof functionToCheck === 'function'
- && !!functionToCheck.constructor
- && !!functionToCheck.call
- && !!functionToCheck.apply
+type SomeFunction = (...args: any[]) => any
+
+const isFunction = (functionToCheck: unknown): functionToCheck is SomeFunction => (
+ typeof functionToCheck === 'function' &&
+ !!functionToCheck.constructor &&
+ !!functionToCheck.call &&
+ !!functionToCheck.apply
)
export default isFunction
diff --git a/src/shared/noop.ts b/src/shared/noop.ts
index b741fc6d..ce4480a9 100644
--- a/src/shared/noop.ts
+++ b/src/shared/noop.ts
@@ -1,6 +1,7 @@
-import { Noop } from './types'
+import { type Noop } from './types'
-const noop: Noop = () => undefined
+/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
+const noop: Noop = (...args: any[]) => undefined
noop.noop = true
diff --git a/src/shared/safelyParseJson.ts b/src/shared/safelyParseJson.ts
index 12794b7e..d7d2c72d 100644
--- a/src/shared/safelyParseJson.ts
+++ b/src/shared/safelyParseJson.ts
@@ -1,4 +1,8 @@
-const safelyParseJson = (parseString: string): T => {
+/**
+ * Safely parse JSON string to object or null
+ * @param parseString
+ */
+const safelyParseJson = (parseString: string): T | null => {
try {
return JSON.parse(parseString)
} catch (e) {
diff --git a/src/shared/types.ts b/src/shared/types.ts
index edbce239..047a7999 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,48 +1,42 @@
export interface Noop {
- noop: true,
+ noop: true
- (): void,
+ (...args: any[]): any
}
/**
* Represent a generic function.
* Used internally to improve code readability
*/
-export interface GenericFunction {
- (...args: any[]): any
-}
+export type GenericFunction = (...args: any[]) => any
/**
* Typed generic callback function, used mostly internally
* to defined callback setters
*/
-export interface SomeCallback {
- (...args: TArgs[]): TResult
-}
+export type SomeCallback = (...args: TArgs[]) => TResult
/**
* A callback setter is generally used to set the value of
* a callback that will be used to perform updates
*/
-export interface CallbackSetter {
- (nextCallback: SomeCallback): void
-}
+export type CallbackSetter = (nextCallback: SomeCallback) => void
/**
* This type is used internally to avoid using directly GeolocationPosition
* as that type is not always compatible with all typescript versions
*/
export interface BRHGeolocationPosition {
- readonly timestamp: number;
+ readonly timestamp: number
readonly coords: {
- readonly accuracy: number;
- readonly altitude: number | null;
- readonly altitudeAccuracy: number | null;
- readonly heading: number | null;
- readonly latitude: number;
- readonly longitude: number;
- readonly speed: number | null;
- };
+ readonly accuracy: number
+ readonly altitude: number | null
+ readonly altitudeAccuracy: number | null
+ readonly heading: number | null
+ readonly latitude: number
+ readonly longitude: number
+ readonly speed: number | null
+ }
}
/**
@@ -50,9 +44,9 @@ export interface BRHGeolocationPosition {
* as that type is not always compatible with all typescript versions
*/
export interface BRHGeolocationPositionError {
- readonly code: number;
- readonly message: string;
- readonly PERMISSION_DENIED: number;
- readonly POSITION_UNAVAILABLE: number;
- readonly TIMEOUT: number;
+ readonly code: number
+ readonly message: string
+ readonly PERMISSION_DENIED: number
+ readonly POSITION_UNAVAILABLE: number
+ readonly TIMEOUT: number
}
diff --git a/src/useAudio.ts b/src/useAudio.ts
index da582faf..c6d45fcd 100644
--- a/src/useAudio.ts
+++ b/src/useAudio.ts
@@ -1,4 +1,4 @@
-import { MutableRefObject, useCallback, useEffect, useRef } from 'react'
+import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
import noop from './shared/noop'
import isClient from './shared/isClient'
import useObjectState from './useObjectState'
@@ -7,74 +7,58 @@ import isAPISupported from './shared/isAPISupported'
import createHandlerSetter from './factory/createHandlerSetter'
import warnOnce from './shared/warnOnce'
-type UseAudioPreloadType = 'auto' | 'metadata' | 'none';
-
-export interface UseAudioOptions {
- loop?: boolean;
- muted?: boolean;
- volume?: number;
- autoPlay?: boolean;
- preload?: UseAudioPreloadType;
- playbackRate?: number;
-}
-
-interface LocalState {
- loop: boolean;
- muted: boolean;
- volume: number;
- duration: number;
- autoPlay: boolean;
- isPlaying: boolean;
- preload?: UseAudioPreloadType;
- currentTime: number;
- playbackRate: number;
- isSrcLoading: boolean | undefined;
-}
-
-interface Controls {
- play: () => void;
- mute: () => void;
- pause: () => void;
- unmute: () => void;
- seek: (time: number) => void;
- onError: (onError: ((error: Error) => void)) => void;
- setVolume: (volume: number) => void;
-}
-
+/**
+ * The default options for the useAudio hook
+ */
const defaultOptions: Required = {
volume: 1,
loop: false,
muted: false,
playbackRate: 1,
autoPlay: false,
- preload: 'auto',
+ preload: 'auto'
}
-const defaultState: LocalState = {
+/**
+ * The default state for the useAudio hook
+ */
+const defaultState: AudioState = {
duration: 0,
currentTime: 0,
isPlaying: false,
isSrcLoading: undefined,
- ...defaultOptions,
+ ...defaultOptions
}
+/**
+ * The error event code to message mapper
+ */
const errorEventCodeToMessageMapper: Record = {
3: 'MEDIA_ERR_DECODE - error occurred when decoding',
4: 'MEDIA_ERR_SRC_NOT_SUPPORTED - audio not supported',
2: 'MEDIA_ERR_NETWORK - error occurred when downloading',
1: 'MEDIA_ERR_ABORTED - fetching process aborted by user',
+ 0: 'UNKNOWN_ERROR - unknown error'
}
-const hookNotSupportedControls: Controls = Object.freeze({
+/**
+ * The hook not supported controls
+ */
+const hookNotSupportedControls: AudioControls = Object.freeze({
seek: noop,
play: noop,
mute: noop,
pause: noop,
unmute: noop,
onError: noop,
- setVolume: noop,
+ setVolume: noop
})
+/**
+ * Checks if the ref element exists and calls the callback with it
+ * @param ref
+ * @param callback
+ */
const checkIfRefElementExists = (ref: MutableRefObject, callback: (element: TElement) => unknown) => () => {
const element = ref.current
@@ -85,11 +69,14 @@ const checkIfRefElementExists = (ref: MutableRefObject, call
return callback(element)
}
+/**
+ * The useAudio hook wraps the Audio API and provides a set of controls to manage the audio
+ */
export const useAudio = (src: string, options?: UseAudioOptions) => {
const hookNotSupportedResponse = [
defaultState,
hookNotSupportedControls,
- useRef(null),
+ useRef(null)
]
if (!isClient) {
@@ -97,36 +84,38 @@ export const useAudio = (src: string, options?: UseAudioOptions) => {
warnOnce('Please be aware that useAudio hook could not be available during SSR')
}
- return hookNotSupportedResponse as [LocalState, Readonly, MutableRefObject]
+ return hookNotSupportedResponse as [AudioState, Readonly, MutableRefObject]
}
if (!isAPISupported('Audio')) {
warnOnce('The current device does not support the \'Audio\' API, you should avoid using useAudio hook')
- return hookNotSupportedResponse as [LocalState, Readonly