@coderebus/react-hooks
v2.0.0-beta.2
Published
A library that provides a bunch of useful custom react hooks as an installable package or a cli that generates a custom shared package for react hooks in your monorepo
Downloads
36
Maintainers
Readme
React Hooks
This package offers two powerful ways to enhance your React development experience:
- Installable Package: Get instant access to a comprehensive library of custom react hooks. Simply install the package to incorporate advanced functionality into your react based applications with minimal effort.
- CLI Tool: Generate a customizable shared react hooks package tailored to your specific needs within a monorepo setup. The CLI tool scaffolds everything you need, allowing you to maintain and scale your development with ease.
Badges from Shields
Table of Contents
- Installation
- Hooks
Installation
#using npm
npm install @coderebus/react-hooks
#using yarn
yarn add @coderebus/react-hooks
#using pnpm
pnpm add @coderebus/react-hooks
useFetch()
useFetch hook is used to make fetch calls. It returns the data, error and loading states. It should be used ideally for 'GET', 'POST', 'PUT', 'PATCH' and 'DELETE' methods.
| Parameter | Required | Type | Default | Description |
| --------- | -------- | -------- | -------------------------------------------------- | ------------------------------------------------ |
| url
| Yes | string
| N.A
| The url to be used for the fetch call |
| options
| No | object
| Default Options
refer | The options object to be used for the fetch call |
Usage
a. GET method
- If you want to use 'GET' method, then you do not have to provide the options object.
- If you are providing the options object, you do not have to explicitly provide the method property, as 'GET' is assumed by default.
import { useFetch } from "@coderebus/react-hooks/fetch";
const { data, error, loading } = useFetch(url);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return <div>{data}</div>;
b. POST (and other mutation methods)
If you want to use any method other than 'GET', then you have to provide the options object with the method and body properties.
const options = {
method: 'POST' (required),
body: {
title: 'foo',
body: 'bar',
} (required)
other similar fetchOptions...
}
const { data, error, loading } = useFetch(url, options)
Default options object
These are the default properties (options) that are used if you do not provide any options object or its properties.
const options = {
method: "GET", // 'POST', 'PUT', 'PATCH'...
headers: {
"Content-Type": "application/json",
},
credentials: "same-origin", // 'omit', 'include'
mode: "cors", // 'no-cors', 'same-origin'
cache: "default", // 'no-cache', 'reload', 'force-cache', 'only-if-cached'
redirect: "follow", // 'manual', 'error'
referrerPolicy: "no-referrer",
refetch: 3, // number of times to refetch in case of error
retryAfter: 1000, // time in milliseconds to wait before retrying
};
useLocalStorage()
useLocalStorage hook is used to store data in the browser's local storage.
| Parameter | Required | Type | Default | Description |
| -------------- | -------- | -------- | ------- | ----------------------------------------------------------- |
| key
| Yes | string
| N.A
| The key to be used to store the data in the session storage |
| initialValue
| No | any
| null
| The initial value to be set in the local storage |
- The hook returns an array of two elements
- The first element is the value stored in the local storage
- The second element is a function to set the value in the local storage
Usage
import { useLocalStorage } from "@coderebus/react-hooks/storage";
const [value, setValue] = useLocalStorage<{ name: string }>("name");
const handleSetValue = () => {
setValue({ name: "Jane Doe" });
};
const handleRemoveValue = () => {
setValue(null);
};
return (
<div>
<button onClick={handleSetValue}>Add Value</button>
<button onClick={handleRemoveValue}>Delete Value</button>
</div>
);
useSessionStorage()
useSessionStorage hook is used to store data in the browser's session storage.
| Parameter | Required | Type | Default | Description |
| -------------- | -------- | -------- | ------- | ----------------------------------------------------------- |
| key
| Yes | string
| N.A
| The key to be used to store the data in the session storage |
| initialValue
| No | any
| null
| The initial value to be set in the session storage |
- The hook returns an array of two elements
- The first element is the value stored in the session storage
- The second element is a function to set the value in the session storage
Usage
import { useSessionStorage } from "@coderebus/react-hooks/storage";
const [tokenId, setTokenId] = useSessionStorage<{ token: string }>("token");
const addTokenId = () => {
setTokenId({ token: "jvV8VIjvhadV73WEVjh7VKHJ798ha" });
};
const removeTokenId = () => {
setTokenId(null);
};
return (
<div>
<button onClick={addTokenId}>Add Token</button>
<button onClick={removeTokenId}>Delete Token</button>
</div>
);
useIntersectionObserver()
useIntersectionObserver hook is used to observe the intersection of a target element with the viewport.
| Parameter | Required | Type | Default | Description |
| ------------------- | -------- | ---------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| elemRef
| No | RefObject<Element>
| useRef<HTMLDivElement>(null)
| The ref of the target element |
| root
| No | Element
| null
| The element that is used as the viewport for checking target's intersection |
| rootMargin
| No | string
| 0%
| The margin around the root |
| threshold
| No | number
or number[]
| 0
| A number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed |
| freezeOnceVisible
| No | boolean
| false
| A boolean value indicating whether the observer should only run once or not |
- The hook returns an array of two elements
- The first element is the
isIntersecting
flag which is true when the target element is intersecting with the viewport - The second element is the target element's
ref
Usage
a. using default values
import { useIntersectionObserver } from "@coderebus/react-hooks/intersection";
const [isIntersecting, targetRef] = useIntersectionObserver(ref, {});
return (
<div>
<div ref={targetRef}>Target Element</div>
<div>{isIntersecting ? "Intersecting" : "Not Intersecting"}</div>
</div>
);
b. using custom values
import { useIntersectionObserver } from "@coderebus/react-hooks/intersection";
import { useRef } from "react";
const ref = useRef<HTMLDivElement | null>(null); // custom ref element
const [isIntersecting] = useIntersectionObserver(ref, {
root: null,
rootMargin: "10px",
threshold: 0.5,
freezeOnceVisible: true,
});
return (
<div>
<div ref={ref}>Target Element</div>
<div>{isIntersecting ? "Intersecting" : "Not Intersecting"}</div>
</div>
);
useDebounce()
useDebounce hook is used to delay the execution of a function until after a certain amount of time has elapsed since its last invocation. Refer here for a detailed explanation on debouncing.
| Parameter | Required | Type | Default | Description |
| --------- | -------- | -------- | ------- | -------------------------------------------------------------- |
| value
| Yes | any
| N.A
| The value to be debounced |
| delay
| No | number
| 500
| The time in milliseconds to wait before executing the function |
The hook returns the debounced value.
Usage
import { ChangeEvent, useState } from "react";
import { useDebounce } from "@coderebus/react-hooks/debounce";
const [searchTerm, setSearchTerm] = useState<string>("");
const debouncedSearch = useDebounce<string>(searchTerm, 500);
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setSearchTerm(e.target.value);
};
return (
<div>
<input
type='text'
value={searchTerm}
onChange={handleChange}
placeholder='Search...'
/>
<div>{debouncedValue}</div>
</div>
);
useThrottle()
useThrottle hook is used to limit the number of times a function can be called in a given time period. Refer here for a detailed explanation on throttling.
| Parameter | Required | Type | Default | Description |
| --------- | -------- | -------- | ------- | --------------------------------------------------- |
| value
| Yes | any
| N.A
| The value to be throttled |
| delay
| No | number
| 500
| The time in milliseconds between the function calls |
The hook returns the throttled value.
Usage
import { useState, useEffect } from "react";
import { useThrottle } from "@coderebus/react-hooks/throttle";
const [scrollPosition, setScrollPosition] = useState(0);
const throttledValue = useThrottle(scrollPosition, 200);
const handleScroll = () => {
setScrollPosition(window.scrollY);
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [handleScroll]);
return (
<div>
<div>{throttledValue}</div>
Scroll Position: {scrollPosition}
</div>
);
useLocalizedContent()
useLocalizedContent hook is used to handle localized content retrieval, caching, and language management.
| Parameter | Required | Type | Default | Description |
| -------------------- | -------- | -------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| url
| Yes | string
| N.A
| The url to be used for the fetch call |
| languageStorageKey
| No | string
| undefined
| The key to be used to store the language in the local storage. If not provided, en_us
is used as the default language. |
| fetchOptions
| No | object
| Default Options
refer | The options object to be used for the fetch call |
- The hook returns an array of three elements.
- The first element is the
loading
flag indicating whether the content is currently loading. - The second element is the
getLabel
function that accepts a label name and returns the corresponding localized content. - The third element is the
getAllLabels
function that returns all localized content for the given URL and language.
Usage
import { useLocalizedContent } from "@coderebus/react-hooks/localization";
import { useLocalStorage } from "@coderebus/react-hooks/storage";
const url = "/data"; // BASE_PATH
const [data, setData] = useLocalStorage("my-language-key", "es_es");
const [loading, getLabel, getAllLabels] = useLocalizedContent(url, "my-language-key");
const title = getLabel("title");
const description = getLabel("description");
const allLabels = getAllLabels();
const changeLanguage = (newLanguage) => {
setData(newLanguage);
};
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
<div>
{Object.entries(allLabels).map(([key, value]) => (
<p key={key}>{`${key}: ${value}`}</p>
))}
</div>
<button onClick={() => changeLanguage("en_us")}>Change to English</button>
</div>
);
useUnmount()
useUnmount hook is used to run a callback (cleanup) function when a component unmounts.
| Parameter | Required | Type | Default | Description |
| --------- | -------- | ------------ | ------- | ----------------------------------------------- |
| fn
| Yes | () => void
| N.A
| The callback function to be executed on unmount |
Usage
import { useUnmount } from "@coderebus/react-hooks/unmount";
const MyComponent = () => {
useUnmount(() => {
// cleanup logic
console.log("Component unmounted");
});
return <div>My Component</div>;
};
useResizeObserver()
useResizeObserver hook is used to observe changes to the size of an element.
| Parameter | Required | Type | Default | Description |
| --------------- | -------- | ---------------------------- | ------- | --------------------------------------------------------------------------- |
| ref
| Yes | RefObject<Element>
| N.A
| The ref of the target element |
| onResize
| No | (size: Size) => void
| null
| Callback function to be executed on resize |
| round
| No | 'round' \| 'ceil' \| 'floor' \| 'toFixed' \| 'trunc'
| N.A
| The rounding method to apply to the observed dimensions |
| toFixedDigits
| No | number
| 0
| Number of decimal places when using toFixed
rounding method |
- The hook returns an object containing the dimensions of the referenced element if
onResize
is not passed in as an argument - The hook does not return anything if
onResize
is passed in as an argument - Size (dimensions) returned consists of
width
,height
,top
,bottom
,left
andright
.
Usage
a. using default values
import { useRef } from "react";
import { useResizeObserver } from "@coderebus/react-hooks/resize";
const MyComponent = () => {
const ref = useRef(null);
const size = useResizeObserver(ref);
return (
<div ref={ref}>
Width: {size?.width}, Height: {size?.height}
</div>
);
};
b. using custom values
import { useState, useRef, useCallback } from "react";
import { useResizeObserver } from "@coderebus/react-hooks/resize";
import { useDebounce } from "@coderebus/react-hooks/debounce";
const MyComponent = () => {
const ref = useRef(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const debouncedResizeHandler = useDebounce(
useCallback((newSize) => {
setSize(newSize);
}, []),
300
);
useResizeObserver(ref, {
onResize: debouncedResizeHandler,
round: 'floor',
});
return (
<div>
<div ref={ref} style={{ resize: 'both', overflow: 'auto', width: '100%', height: '100px', border: '1px solid black' }}>
Resize me!
</div>
<div>
Width: {size.width}, Height: {size.height}
</div>
</div>
);
};
export default MyComponent;
useDocumentTitle()
useDocumentTitle hook is used to update the document title.
| Parameter | Required | Type | Default | Description |
| --------- | -------- | -------- | ------- | --------------------------- |
| title
| Yes | string
| N.A
| The title to set |
Usage
import { useDocumentTitle } from "@coderebus/react-hooks/title";
const MyComponent = () => {
useDocumentTitle("My New Title");
return <div>Check the document title</div>;
};
useMediaQuery()
useMediaQuery hook is used to manage and respond to media queries.
| Parameter | Required | Type | Default | Description |
| ------------------------ | -------- | -------- | ------- | --------------------------------------------------------------- |
| query
| Yes | string
| N.A
| The media query string to match |
| defaultValue
| No | boolean
| false
| The default value to use when initializing on the server |
| initializeWithValue
| No | boolean
| true
| Determines whether the state should be initialized with the current match value of the media query when the component mounts |
- The hook returns a boolean indicating whether the media query matches.
Server Side Rendering
defaultValue
: This is used to set a default value for the media query match when the code is running on the server. Since window is not available on the server, you'll want to provide a sensible defaultValue to prevent errors and ensure your components render correctly during initial page load.
initializeWithValue
: This option determines whether the hook should initialize the state with the current match value of the media query when the component mounts.If you want your UI to respond instantly to the media query on the initial render, set initializeWithValue to true (default). To avoid potential layout shifts or performance issues (or in SSR), set initializeWithValue to false.import { useMediaQuery } from "@coderebus/react-hooks/media"; const MyComponent = () => { const isLargeScreen = useMediaQuery("(min-width: 1024px)", { defaultValue: true, initializeWithValue: false, }); return <div>{isLargeScreen ? "Large Screen" : "Small Screen"}</div>; };
Usage
import { useMediaQuery } from "@coderebus/react-hooks/media";
const MyComponent = () => {
const isLargeScreen = useMediaQuery("(min-width: 1024px)");
return <div>{isLargeScreen ? "Large Screen" : "Small Screen"}</div>;
};
useIsomorphicLayoutEffect
useIsomorphicLayoutEffect hook is a safe version of useLayoutEffect
for SSR (Server-Side Rendering) environments. It uses useLayoutEffect
on the client and useEffect
on the server to avoid warnings about the use of useLayoutEffect
in SSR.
Usage
import { useIsomorphicLayoutEffect } from "@coderebus/react-hooks/isomorphic";
const MyComponent = () => {
useIsomorphicLayoutEffect(() => {
console.log("Layout effect");
}, []);
return <div>Check the console</div>;
};
useClipboard()
useClipboard hook is used to copy text to the clipboard.
| Parameter | Required | Type | Default | Description |
| --------- | -------- | -------- | ------- | --------------------------------- |
| timeout
| No | number
| 2000
| The time (in milliseconds) before the copied state resets |
- The hook returns an object with the following properties:
copy
: A function to copy the specified text to the clipboard.reset
: A function to reset the copied and error states.error
: AnError
object if the copy operation failed, ornull
if it succeeded.copied
: A boolean indicating whether the copy operation was successful.
Usage
import { useClipboard } from "@coderebus/react-hooks/clipboard";
const MyComponent = () => {
const { copy, reset, error, copied } = useClipboard({ timeout: 3000 });
return (
<div>
<button onClick={() => copy("Hello, World!")}>Copy Text</button>
{copied && <span>Copied to clipboard!</span>}
{error && <span>Error: {error.message}</span>}
<button onClick={reset}>Reset</button>
</div>
);
};
export default MyComponent;