Utility hooks to be used in the application.
npm install @thecolvinco/react-hooksUtility hooks to be used in the application.
> React 17^ | 18^
``node`
pnpm install @thecolvinco/react-hooks
If you need to skip the first render of functional component _(the equivalent of componentDidMount method in class component)_, useDidUpdateEffect hook is right for the job.
`tsx
export default function () {
const [state, setState] = useState({ name: '' });
useDidUpdateEffect(() => {
setState(user);
}, [user]);
}
`
useDisclosure is a custom hook used to help handle common open, close, or toggle scenarios. It can be used to control feedback component such as Modal, AlertDialog, ...
`tsx
import { useDisclosure } from '@thecolvinco/hooks';
const { isOpen, onOpen, onClose } = useDisclosure();
`
Hook to assist in HTTP requests and manage errors, data, and request loading status.
First param of useHttpState is a fetchData receives the request and the hook itself captures the errors. The second parameter is the array of dependencies to return execute the request.
`tsx
import { useHttpState } from '@thecolvinco/hooks';
const userId = '6cae06dc-47bb-4bbc-8a40-25ebda2213cc';
const { error, data, isLoading } = useHttpState(() => {
return axios('//acme.inc/api');
}, [userId]);
return isLoading ? 'Loading...' : error || data;
`
React hook to check if the component is still mounted.
`tsx
import { useIsMounted } from '@thecolvinco/hooks';
const isMounted = useIsMounted();
useEffect(() => {
const fetchData = async () => {
const { data } = await axios('//acme.inc/api');
if (isMounted) {
setData(data);
}
};
fetchData();
}, [isMounted]);
`
React hook to detect the device type. This hook is able to detect mobile, desktop, android or iOS device.
`tsx
import { useMobileDetect } from '@thecolvinco/hooks';
const isMobile = useMobileDetect();
return isMobile ? 'Short text' : 'Long more text explanation';
`
###Β useOnScreen
This hook allows you to easily detect when an element is visible on the screen as well as specify how much of the element should be visible before being considered on screen.
`tsx
import { useState, useEffect, useRef, type MutableRefObject } from 'react';
export default function () {
const ref = useRef
const isVisible = useOnScreen(ref, '-300px');
return (
$3
useOutsideClick is a custom hook that handles click events outside a specific DOM element, like a div. A handler is invoked when a click or touch event happens outside the referenced element.This hook is compatible with mouse and touch events.
`tsx
import { useRef, useState } from 'react';
import { useOutsideClick } from '@thecolvinco/hooks';const ref = useRef();
const [isModalOpen, setIsModalOpen] = useState(false);
useOutsideClick({
ref,
handler: () => setIsModalOpen(false),
});
``