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
npm install @coderebus/react-hooksbash
#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 |
$3
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.
`jsx
import { useFetch } from "@coderebus/react-hooks/fetch";
const { data, error, loading } = useFetch(url);
if (loading) {
return Loading...;
}
if (error) {
return Error: {error};
}
return {data};
`
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.
`jsx
const options = {
method: 'POST' (required),
body: {
title: 'foo',
body: 'bar',
} (required)
other similar fetchOptions...
}
const { data, error, loading } = useFetch(url, options)
`
$3
These are the default properties (options) that are used if you do not provide any options object or its properties.
`jsx
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
$3
`jsx
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 (
);
`
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
$3
`jsx
import { useSessionStorage } from "@coderebus/react-hooks/storage";
const [tokenId, setTokenId] = useSessionStorage<{ token: string }>("token");
const addTokenId = () => {
setTokenId({ token: "jvV8VIjvhadV73WEVjh7VKHJ798ha" });
};
const removeTokenId = () => {
setTokenId(null);
};
return (
);
`
useIntersectionObserver()
useIntersectionObserver hook is used to observe the intersection of a target element with the viewport.
| Parameter | Required | Type | Default | Description |
| ------------------- | -------- | ---------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| elemRef | No | RefObject | useRef | 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
$3
a. using default values
`jsx
import { useIntersectionObserver } from "@coderebus/react-hooks/intersection";
const [isIntersecting, targetRef] = useIntersectionObserver(ref, {});
return (
Target Element
{isIntersecting ? "Intersecting" : "Not Intersecting"}
);
`
b. using custom values
`jsx
import { useIntersectionObserver } from "@coderebus/react-hooks/intersection";
import { useRef } from "react";
const ref = useRef(null); // custom ref element
const [isIntersecting] = useIntersectionObserver(ref, {
root: null,
rootMargin: "10px",
threshold: 0.5,
freezeOnceVisible: true,
});
return (
Target Element
{isIntersecting ? "Intersecting" : "Not Intersecting"}
);
`
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.
$3
`jsx
import { ChangeEvent, useState } from "react";
import { useDebounce } from "@coderebus/react-hooks/debounce";
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearch = useDebounce(searchTerm, 500);
const handleChange = (e: ChangeEvent) => {
setSearchTerm(e.target.value);
};
return (
type='text'
value={searchTerm}
onChange={handleChange}
placeholder='Search...'
/>
{debouncedValue}
);
`
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.
$3
`jsx
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 (
{throttledValue}
Scroll Position: {scrollPosition}
);
`
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.
$3
`jsx
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 Loading...;
}
return (
{title}
{description}
{Object.entries(allLabels).map(([key, value]) => (
{${key}: ${value}}
))}
);
`
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 |
$3
`jsx
import { useUnmount } from "@coderebus/react-hooks/unmount";
const MyComponent = () => {
useUnmount(() => {
// cleanup logic
console.log("Component unmounted");
});
return My Component;
};
`
useResizeObserver()
useResizeObserver hook is used to observe changes to the size of an element.
| Parameter | Required | Type | Default | Description |
| --------------- | -------- | ---------------------------- | ------- | --------------------------------------------------------------------------- |
| ref | Yes | RefObject | 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 and right.
$3
a. using default values
`jsx
import { useRef } from "react";
import { useResizeObserver } from "@coderebus/react-hooks/resize";
const MyComponent = () => {
const ref = useRef(null);
const size = useResizeObserver(ref);
return (
Width: {size?.width}, Height: {size?.height}
);
};
`
b. using custom values
`jsx
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 (
Resize me!
Width: {size.width}, Height: {size.height}
);
};
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 |
$3
`jsx
import { useDocumentTitle } from "@coderebus/react-hooks/title";
const MyComponent = () => {
useDocumentTitle("My New Title");
return Check the document title;
};
`
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.
>
> `jsx
> import { useMediaQuery } from "@coderebus/react-hooks/media";
>
> const MyComponent = () => {
> const isLargeScreen = useMediaQuery("(min-width: 1024px)", {
> defaultValue: true,
> initializeWithValue: false,
> });
>
> return {isLargeScreen ? "Large Screen" : "Small Screen"};
> };
> `
$3
`jsx
import { useMediaQuery } from "@coderebus/react-hooks/media";
const MyComponent = () => {
const isLargeScreen = useMediaQuery("(min-width: 1024px)");
return {isLargeScreen ? "Large Screen" : "Small Screen"};
};
`
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.
$3
`jsx
import { useIsomorphicLayoutEffect } from "@coderebus/react-hooks/isomorphic";
const MyComponent = () => {
useIsomorphicLayoutEffect(() => {
console.log("Layout effect");
}, []);
return Check the console;
};
`
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: An Error object if the copy operation failed, or null if it succeeded.
- copied: A boolean indicating whether the copy operation was successful.
$3
`jsx
import { useClipboard } from "@coderebus/react-hooks/clipboard";
const MyComponent = () => {
const { copy, reset, error, copied } = useClipboard({ timeout: 3000 });
return (
{copied && Copied to clipboard!}
{error && Error: {error.message}}
);
};
export default MyComponent;
``