Skip to content

Instantly share code, notes, and snippets.

@cheskoxd
cheskoxd / useInactivityTimeout.tsx
Last active June 22, 2024 14:14
Small hook to check if the user has been inactive for x hours it will reload the page
import { useEffect, useRef } from 'react';
const useInactivityTimeout = (timeoutInHours) => {
const timeoutInMillis = timeoutInHours * 60 * 60 * 1000;
const timer = useRef(null);
useEffect(() => {
if (navigator.userActivation) {
if(navigator.userActivation.isActive){
if (timer.current) {
import { useState } from "react";
export const useClipboard = () => {
const [isCopied, setIsCopied] = useState(false);
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text).then(
() => setIsCopied(true),
() => setIsCopied(false)
);
import { useEffect, useState } from "react";
export const useFetch = <T>(url: string) => {
const [data, setData] = useState<T | any>();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
import { useState } from "react";
export const useToggle = (initialValue: boolean = false) => {
const [value, setValue] = useState<boolean>(initialValue);
const toggle = () => {
setValue((prevValue) => !prevValue);
};
return [value, toggle] as const;
import { useEffect, useRef } from "react";
export const usePrevious = <T>(value: T) => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
import { useEffect, useState } from "react";
export const useOnlineStatus = () => {
const [isOnline, setIsOnline] = useState(navigator.onLine);
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
useEffect(() => {
window.addEventListener("online", handleOnline);