A collection of useful custom react hooks for API data fetching, local storage usage, customized DOM manipulations, etc.
One can install the hooks' collection as an NPM package as follows:
npm install simple-custom-react-hooks
This custom hook covers the "missing" case of the build-in useEffect()1 hook of running only if an update occurs.
A custom hook that stores a state into the local storage2.
A custom hook that performs an API fetch3 to retrive all the resources available at a given URL and persists the response in a local state.
A custom hook that performs an API fetch3 to retrieve a single resource available at a given URL and persists the response in a local state.
A custom React Query (TanStack Query) -like hook that executes and async function and persists the response in a local state.
A custom hook that detects a click that is performed outside of an HTML element. This might be especially handy when dealing with select/drop-down elements, when one would like to detect a user movement outside of the eleemnt and perform certain actions (e.g. auto-close an opened select).
A custom hook that toggles a boolean flag.
A custom hook that keeps track of the size of the DOM's window width.
A custom hook that keeps track of the size of the DOM's window height.
A custom hook that keeps track of the scroll position.
A custom hook that updates a state value after some user-specified amount of time has passed. This might be especially useful for input elements that are coupled with some search functionality.
A custom hook that returns the previous value of a variable within a functional component (e.g. a local state)
A custom hook that returns a ref for an HTML input element as well as a function to focus the input field.
A custom hook that keeps track of the current pointer position on the screen.
A custom hook checks whether a user is online by subscribing to the global online (and offline) event(s).
A custom hook that handles form input fields' logic.
A custom hook checks whether a user is online by subscribing to the global online (and offline) event(s) with the help of the build-in react useExternalStore hook.
A generic custom hook based on the built-in useEffect function that accepts and executes an async function.
const someProp = `foo`
useEffectUpdate({
callback: () => {
// Effect code goes here
},
dependencies: [someProp],
})const [localStorageValue, setLocalStorageValue] = useLocalStorage(`foo`)
...
setLocalStorageValue(`bar`)const BASE_URL = `foo`
const RESOURCE_PATH = `bar`
const [{ data, isError, isLoading }, { setQueryParameters, shouldFetchData }] = useFetchAll(BASE_URL}/${RESOURCE_PATH}`)const BASE_URL = `foo`
const RESOURCE_PATH = `bar`
const RESOURCE_ID = `123`
const [{ data, isError, isLoading }, { setQueryParameters, shouldFetchData }] = useFetchAll(BASE_URL}/${RESOURCE_PATH}/${RESOURCE_ID}`)Note: keep in mind that this is a sample usage. The body of the queryFn can contain different logic, e.g. one can make an API call using an external library of own choice such as axios4.
const URL = `foo`
const queryKey = `bar`
const [{ data, isLoading, isError }] = useQuery({
initialData: [],
queryFn: async () => {
const response = await fetch(`${URL}`)
const responseData = await response.json()
return responseData
},
queryKey: [queryKey],
})// Handles "outside" click logic (e.g. close an opened select)
const handleClickOutside = () => { ... }
...
const ref = useClickOutside({ callback: handleClickOutside })
...
return (
<select id="myDropdown" ref={ref}>
<option value="option1">Option 1</option>
<option value="option1">Option 1</option>
</select>
)const [booleanValue, toggleBooleanValue] = useToggleBoolean(true)
...
// e.g. toggle the value once a click event occurs
const handleClick = () => { toggleBooleanValue() }const windowWidth = useWindowWidth() const windowHeight = useWindowHeight() const scrollPosition = useScrollPosition() const value = useDebounce(inputValue, 100) const [count, setCount] = useState(0)
...
const previousValue = usePreviousValue(count) // Holds the "previous" state const { inputRef, focusInput } = useInputFocus()
const handleClick = () => {
...
focusInput()
}
...
return (
<>
<button onClick={handleClick}>Click</button>
<input ref={inputRef} placeholder="Search"/>
</>
)const pointerPosition = usePointerPosition() const isOnline = useOnlineStatus() const { formField, onChange } = useFormInput() const isOnline = useOnlineStatusExternalStore() const { result, isLoading, error } = useAsyncEffect(() => {
return new Promise((resolve, reject) => {
const isResolved = false
setTimeout(() => isResolved ? resolve("resolve") : reject("Error"), 1000)
}
}) API
In the following objArg: Args<T> is used to describe the object argument that is passed to the hook.
Type: Array<T>
Type: () => void
Type: string
Type: string
Type: QueryParams
Default value: { limit: 100 }: QueryParams
type QueryParams = {
limit: number
page?: number
sort?: Sort
}
type Sort = {
sortOrder: SortOrderEnum
sortField: string
}
enum SortOrderEnum {
asc = `ASC`,
DESC = `DESC`
}Type: Array<T>
Default value: []
Type: string
Type: string
Type: object
In the following objArg is used to describe the object argument passed to the hook.
Type: Array<T>
Type: Array<string>
Type: () => Promise<T>
In the following objArg is used to describe the object that is passed to the hook.
Type: () => void
Type: boolean
Type: number
Type: number
Type: number
Type: string
Type: number
Type: JSValueType = string | boolean | number
Type: { positionX: number, positionY: number }
Type: boolean
Type: String
Type: () => Promise
Type: Array<number | string>
Footnotes
-
React
useEffect- React use effect hook ↩ -
MDN documentation about local storage - Local Storage MDN ↩
-
MDN fetch API - Fetch API MDN ↩ ↩2
-
axios GitHub - axios GitHub repository ↩