@ptenn/react-hooks
Reusable custom hooks for React
Install
yarn add @ptenn/react-hooks
Build
yarn build
Lint
yarn lint
Publish
Runs a build process under the prepublishOnly
script.
npm publish
Usage
useIsClient
Determines if the client has been mounted.
const isClient = useIsClient()
// browser
console.log(isClient); // true
// server
console.log(isClient); // false
useScript
Loads a <script>
element into the document and manages its status.
const status = useScript('https://code.jquery.com/jquery-3.5.1.min.js');
if (status === 'ready') {
// do something
}
useSSR
Determines if the code is being executed in the browser or on the server.
const ssrStatus = useSSR();
// browser
console.log(ssrStatus.isBrowser); // true
console.log(ssrStatus.isServer); // false
// server
console.log(ssrStatus.isBrowser); // false
console.log(ssrStatus.isServer); // true
useIsomorphicLayoutEffect
Returns effect based on the environment useLayoutEffect is used on the browser useEffect is used on the server
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';
useIsomorphicLayoutEffect(() => {
// effect here
}, []);
useEventListener
Attaches an event to the window, document, element Removes the event listener on cleanup
const handleResize = () => {
// do something
}
useEventListener('resize', handleResize, window);
useHover
Determines if the mouse is in the hover element
function HoverElement() {
const divRef = useRef();
const isHovering = useHover(divRef);
return (
<div ref={divRef}>
{isHovering ? 'hovering', : 'not hovering'}
</div>
);
}