All react.js custom hooks you frequently use.
npm install use-any-hook

A collection of commonly used custom React.js hooks for various use cases in front-end development.
You can install the package using npm:
``bash`
npm install use-any-hook
Thi is a quide through the usage process, jump directly to the hook you want:
###### useFetch
###### useDebounce
###### useClickOutside
###### useLocalStorageWithExpiry
###### useForm
###### useDarkMode
###### useInfiniteScroll
###### useMousePosition
###### useGeoLocation
###
A quick quide for each hook in the use-any-hook package
`javascript`
// Import your desired custom hook 1st.
import { useInfiniteScroll } from "use-any-hook";
useFetch is a hook for making HTTP requests and managing the loading and error state of the fetched data.
`javascript
function MyComponent() {
const [data, loading, error] = useFetch("https://api.example.com/data");
useEffect(() => {
// Handle data when it is available
if (data) {
// Do something with the fetched data
}
}, [data]);
return (
$3
useDebounce is a hook that allows you to debounce a value or function to delay its execution until a certain timeout has passed.`javascript
function MyComponent() {
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearchTerm = useDebounce(searchTerm, 1000); const handleSearch = async () => {
const response = await fetch(
https://dummyjson.com/products/search?q=${debouncedSearchTerm}
);
}; useEffect(() => {
handleSearch();
// This will be called after (1000ms = 1second) from your last keypress
}, [debouncedSearchTerm]);
return (
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
`$3
useClickOutside detects clicks outside of a specified element and triggers a callback.`typescript
function MyComponent() {
const myRef = useRef(null); const handleClickOutside = () => {
console.log("Clicked outside the element");
};
useClickOutside(myRef, handleClickOutside);
return (
{/ Your content here /}
);
}
`$3
useLocalStorageWithExpiry extends useLocalStorage to store values with an expiration time.`typescript
function MyComponent() {
const [data, setData] = useState(''); const { value, setStoredValue } = useLocalStorageWithExpiry('key', 'initialValue', 3000); // Expire after 3 seconds
useEffect(() => {
if (value) {
// Use the retrieved data
console.log('Data from localStorage:', value);
setData(value); // Set the component state with retrieved data
}
}, [value]);
const handleSaveData = (newData: string) => {
setData(newData);
setStoredValue(newData);
};
return (
setData(e.target.value)} />
);
}
`$3
useForm is a hook for handling form input state and simplifying form management.`javascript
function MyComponent() {
const { values, handleChange, resetForm } = useForm({
username: "",
}); const handleSubmit = (e) => {
e.preventDefault();
// Use the form values for submission
console.log("Submitted data:", values);
};
return (
);
}
`$3
useDarkMode is a hook for managing the theme, such as toggling between light and dark mode.`javascript
function MyComponent() {
const { isDarkMode, toggleTheme } = useDarkMode(); // toggleTheme() function toggles the body tag className too.
//
return (
{isDarkMode ? "Dark Mode" : "Light Mode"}
);
}
`$3
useInfiniteScroll This hook helps you implement infinite scrolling in your application, fetching and appending data as the user scrolls.`javascript
function InfiniteScrollExample() {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1); // Simulated function to fetch more data
const fetchMoreData = async () => {
// Simulated API call to fetch more items (e.g., from a backend server)
const response = await fetch(
https://api.example.com/items?page=${page});
const newData = await response.json(); // Update the items and page
setItems([...items, ...newData]);
setPage(page + 1);
};
const isFetching = useInfiniteScroll(fetchMoreData);
useEffect(() => {
// Initial data fetch when the component mounts
fetchMoreData();
}, []);
return (
{items.map((item, index) => (
- {item}
))}
{isFetching && Loading more items...
}
);
}
`$3
useMousePosition is a hook for detecting the mouse position in a specific div x,y axis.`javascript
function MyComponent() {
const ref = React.useRef(null);
const { x, y } = useMousePosition(ref); return (
Mouse Position: x-axis: ${x}, y-axis: ${x}
);
}
`$3
useGeoLocation is a hook for detecting the user accurate position in latitude and longitude after asking for permission.`javascript
function MyComponent() {
const { location, error } = useGeoLocation(); if (error) {
return
Error: {error.message};
} return (
{location ? (
Latitude: {location.coords.latitude}, Longitude: {location.coords.longitude}
) : (
Fetching location...
)}
);
}
``