use-any-hook
v1.3.5
Published
All react.js custom hooks you frequently use.
Downloads
9
Maintainers
Readme
useAnyHook();
A collection of commonly used custom React.js hooks for various use cases in front-end development.
Installation
You can install the package using npm:
npm install use-any-hook
Content Summary
Thi is a quide through the usage process, jump directly to the hook you want:
useFetch
useDebounce
useClickOutside
useLocalStorageWithExpiry
useForm
useDarkMode
useInfiniteScroll
useMousePosition
useGeoLocation
Usage
A quick quide for each hook in the use-any-hook package
// Import your desired custom hook 1st.
import { useInfiniteScroll } from "use-any-hook";
1. useFetch
useFetch
is a hook for making HTTP requests and managing the loading and error state of the fetched data.
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 (
<div>
{loading ? "Loading..." : null}
{error ? "Error: Unable to fetch data" : null}
{data ? <div>Data: {data}</div> : null}
</div>
);
}
2. useDebounce
useDebounce
is a hook that allows you to debounce a value or function to delay its execution until a certain timeout has passed.
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 (
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
3. useClickOutside
useClickOutside
detects clicks outside of a specified element and triggers a callback.
function MyComponent() {
const myRef = useRef<HTMLDivElement>(null);
const handleClickOutside = () => {
console.log("Clicked outside the element");
};
useClickOutside(myRef, handleClickOutside);
return (
<div className="p-14 bg-red-500" ref={myRef}>
{/* Your content here */}
</div>
);
}
4. useLocalStorageWithExpiry
useLocalStorageWithExpiry
extends useLocalStorage to store values with an expiration time.
function MyComponent() {
const [data, setData] = useState<string | null>('');
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 (
<div>
<input value={data || ''} onChange={(e) => setData(e.target.value)} />
<button onClick={() => handleSaveData(data)}>Save Data</button>
</div>
);
}
5. useForm
useForm
is a hook for handling form input state and simplifying form management.
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 (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={values.username}
onChange={handleChange}
placeholder="Username"
/>
<button type="submit">Submit</button>
<button type="button" onClick={resetForm}>
Reset
</button>
</form>
);
}
6. useDarkMode
useDarkMode
is a hook for managing the theme, such as toggling between light and dark mode.
function MyComponent() {
const { isDarkMode, toggleTheme } = useDarkMode();
// toggleTheme() function toggles the body tag className too.
// <body className="dark"></body>
return (
<div className={isDarkMode ? "dark-mode" : "light-mode"}>
<button onClick={toggleTheme}>Toggle Theme</button>
{isDarkMode ? "Dark Mode" : "Light Mode"}
</div>
);
}
7. useInfiniteScroll
useInfiniteScroll
This hook helps you implement infinite scrolling in your application, fetching and appending data as the user scrolls.
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 (
<div>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
{isFetching && <p>Loading more items...</p>}
</div>
);
}
8. useMousePosition
useMousePosition
is a hook for detecting the mouse position in a specific div x,y axis.
function MyComponent() {
const ref = React.useRef(null);
const { x, y } = useMousePosition(ref);
return (
<div ref={ref}>
Mouse Position: `x-axis: ${x}, y-axis: ${x}`
</div>
);
}
9. useGeoLocation
useGeoLocation
is a hook for detecting the user accurate position in latitude and longitude after asking for permission.
function MyComponent() {
const { location, error } = useGeoLocation();
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{location ? (
<div>
Latitude: {location.coords.latitude}, Longitude: {location.coords.longitude}
</div>
) : (
<div>Fetching location...</div>
)}
</div>
);
}