A type safe, functional, and easy to use utility library for React Hooks.
Explore the docs »
View Demo
·
Report Bug
·
Request Feature
This project is a collection of React Hooks that I have found useful in my own projects. I hope you find them useful as well!. The idea is to build a library of hooks that are easy to use, type safe, and functional.
npm i @julianfere/hooked
useAsync is a custom React hook designed to simplify the management of asynchronous operations in React components. It provides a clean and consistent way to handle asynchronous function calls and their associated states.
import React from "react";
import { useAsync } from "@julianfere/hooked";
const fetchData = async () => {
// Your asynchronous operation here
// e.g., fetching data from an API
};
const BasicExampleAutomatic = () => {
const { state } = useAsync(() => fetchData());
return (
<>
{state === "pending" && <p>Loading...</p>}
{state === "fulfilled" && <p>Data loaded successfully!</p>}
{state === "rejected" && <p>Error loading data.</p>}
</>
);
};
const CompleteExampleManua = () => {
const [data, setData] = useState(null);
const { run, state } = useAsync(() => fetchData(), {
manual: true,
onSuccess: (data) => setData(data),
onError: (error) => console.log(error),
});
return (
<>
{state === "pending" && <p>Loading...</p>}
{state === "fulfilled" && <p>Data loaded successfully!</p>}
{state === "rejected" && <p>Error loading data.</p>}
<button onClick={run}>Fetch Data</button>
</>
);
};
const { run, state } = useAsync(() => asyncFunction(), options);
asyncFunction
: The asynchronous function that will be executed.
options
: (Optional) Configuration options for the useAsync hook.
Options:
manual
(default: false): If set to true, the asynchronous function won't run automatically on component mount. You must call run manually. Otherwise, the asynchronous function will run automatically on component mount.
onSuccess
: A callback function that will be executed when the asynchronous function resolves successfully.
onError
: A callback function that will be executed when the asynchronous function encounters an error.
cancelable
: (default: true) If set to false, the asynchronous function will not be cancelable. If set to true, the asynchronous function will be cancelable. This means that if the component unmounts before the asynchronous function resolves, the asynchronous function will be canceled.
Returned Values:
run
: A function that triggers the execution of the asynchronous function. If manual is set to true, this function will throw an error, reminding you to set manual to true.
state
: A string representing the current state of the asynchronous operation. Possible values are idle, pending, fulfilled, or rejected.
useDebounce is a custom React hook designed to simplify the management of debounced values in React components. It provides a clean and consistent way to handle debounced values and their associated states.
import React, { useState } from "react";
import { useDebounce } from "@hooks";
const BasicExample = () => {
const [value, setValue] = useState("");
const debouncedValue = useDebounce(value, 500);
useEffect(() => { makeApiCall(debouncedValue); }, [debouncedValue]);
return (
<>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<p>Debounced value: {debouncedValue}</p>
</>
);
};
const debouncedValue = useDebounce(value, delay);
value
: The value to be debounced.
delay
: The delay in milliseconds to wait before updating the debounced value. Defaults to 500ms.
useThrottle is a custom React hook designed to simplify the management of throttled values in React components. It provides a clean and consistent way to handle throttled values and their associated states.
import React, { useState } from "react";
import { useThrottle } from "@hooks";
const BasicExample = () => {
const [value, setValue] = useState("");
const throttledValue = useThrottle(value, 500);
useEffect(() => { makeApiCall(throttledValue); }, [throttledValue]);
return (
<>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<p>Throttled value: {throttledValue}</p>
</>
);
};
const throttledValue = useThrottle(value, delay);
value
: The value to be throttled.
delay
: The delay in milliseconds to wait before updating the throttled value. Defaults to 500ms.
useLocalStorage is a custom React hook designed to simplify the management of local storage in React components. It provides a clean and consistent way to handle local storage and its associated states.
import { useLocalStorage } from "@hooks";
type UseLocalStorageType = {
name: string;
age: number;
}
const BasicExample = () => {
const { getItem, setItem, removeItem, hasItem, clear } = useLocalStorage<UseLocalStorageType>();
const [key, setKey] = useState("");
const [value, setValue] = useState("");
return (
<>
<input onChange={(e) => setKey(e.value)} />
<input onChange={(e) => setValue(e.value)} />
<p>{key} is {getItem(key)}</p>
<button onClick={() => setItem(key, value)}>Set Item</button>
<button onClick={() => removeItem(key)}>Remove Item</button>
<button onClick={() => clear()}>Clear</button>
</>
);
};
const { getItem, setItem, removeItem, hasItem, clear } = useLocalStorage<T>();
T
: The type of the value to be stored in local storage.
Returned Values:
getItem
: A function that retrieves the value associated with the specified key from local storage.
setItem
: A function that stores the specified value in local storage, associated with the specified key.
removeItem
: A function that removes the specified key and its associated value from local storage.
hasItem
: A function that returns true if the specified key exists in local storage, and false otherwise.
clear
: A function that removes all keys and their associated values from local storage.
useDelay is a custom React hook designed to simplify the management of delayed values in React components. It provides a clean and consistent way to handle delayed values and their associated states.
import {useDelay} from "@hooks";
const BasicExample = () => {
const [value, setValue] = useState("");
const updateValue = (val: string) => setValue(val)
useDelay(() => updateValue("Delayed value"));
const runDelay = useDelay(() => updateValue("Manual value"), {manual: true, delay: 1000});
return <h1>Delayed Value: {value}</h1>
}
const debouncedValue = useDebounce(value, delay);
value
: The value to be debounced.
delay
: The delay in milliseconds to wait before updating the debounced value. Defaults to 500ms.
useThrottle is a custom React hook designed to simplify the management of throttled values in React components. It provides a clean and consistent way to handle throttled values and their associated states.
import React, { useState } from "react";
import { useThrottle } from "@hooks";
const BasicExample = () => {
const [value, setValue] = useState("");
const throttledValue = useThrottle(value, 500);
useEffect(() => { makeApiCall(throttledValue); }, [throttledValue]);
return (
<>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<p>Throttled value: {throttledValue}</p>
</>
);
};
const throttledValue = useThrottle(value, delay);
value
: The value to be throttled.
delay
: The delay in milliseconds to wait before updating the throttled value. Defaults to 500ms.
useLocalStorage is a custom React hook designed to simplify the management of local storage in React components. It provides a clean and consistent way to handle local storage and its associated states.
import { useLocalStorage } from "@hooks";
type UseLocalStorageType = {
name: string;
age: number;
}
const BasicExample = () => {
const { getItem, setItem, removeItem, hasItem, clear } = useLocalStorage<UseLocalStorageType>();
const [key, setKey] = useState("");
const [value, setValue] = useState("");
return (
<>
<input onChange={(e) => setKey(e.value)} />
<input onChange={(e) => setValue(e.value)} />
<p>{key} is {getItem(key)}</p>
<button onClick={() => setItem(key, value)}>Set Item</button>
<button onClick={() => removeItem(key)}>Remove Item</button>
<button onClick={() => clear()}>Clear</button>
</input>
);
};
const { getItem, setItem, removeItem, hasItem, clear } = useLocalStorage<T>();
T
: The type of the value to be stored in local storage.
Returned Values:
getItem
: A function that retrieves the value associated with the specified key from local storage.
setItem
: A function that stores the specified value in local storage, associated with the specified key.
removeItem
: A function that removes the specified key and its associated value from local storage.
hasItem
: A function that returns true if the specified key exists in local storage, and false otherwise.
clear
: A function that removes all keys and their associated values from local storage.
useDelay is a custom React hook designed to simplify the management of delayed values in React components. It provides a clean and consistent way to handle delayed values and their associated states.
import {useDelay} from "@hooks";
const BasicExample = () => {
const [value, setValue] = useState("");
const updateValue = (val: string)=> {
setValue(val);
}
useDelay(() => updateValue("Delayed value"));
const runDelay = useDelay(() => updateValue("Manual value"), {manual: true, delay: 1000});
return (
<>
<button onClick={runDelay}>Run manual delay</button>
<p>Delayed value: {delayedValue}</p>
</>
);
};
const delayedValue = useDelay(callback, options);
callback
: The function to be delayed.
options
: (Optional) Configuration options for the useDelay hook.
manual
(default: false): If set to true, the delayed function won't run automatically on component mount. You must call run manually. Otherwise, the delayed function will run automatically on component mount.delay
: The delay in milliseconds to wait before running the delayed function. Defaults to 250ms.
Returned Values:
run
: A function that triggers the execution of the delayed function. If manual is set to true, this function will throw an error, reminding you to set manual to true.
useDocumentTitle is a custom React hook designed to simplify the management of the document title in React components. It provides a clean and consistent way to handle the document title and its associated states.
import {useDocumentTitle} from "@hooks";
const BasicExample = () => {
useDocumentTitle("New Title");
return (
<>
<p>Document title has been updated to "New Title"</p>
</>
);
};
useDocumentTitle(title, persistOnUnmount);
title
: The new title for the document.
persistOnUnmount
: (Optional) If set to true, the document title will persist after the component unmounts. Defaults to false.
EventContext is a custom context with a generic type that allows you to create a global event emitter in your React application. It provides a clean and consistent way to handle global events and their associated states.
import { factory } from "@julianfere/hooked/events";
import { User, Post } from "./entitites";
interface AppEvents {
userLoggedIn: User;
userLoggedOut: never;
postCreated: Post;
}
// this creates the factory for the context, provider, and hook with the specified events passed as a generic type
const { createEventContext, createEventHook, createEventProvider } =
factory<AppEvents>();
// this creates the context, provider, and hook with the specified events passed as a generic type
const EventContext = createEventContext();
const EventsProvider = createEventProvider(EventContext);
export const useEvents = createEventHook(EventContext);
const App = () => {
return (
<EventsProvider>
<UserComponent />
<PostComponent />
</EventsProvider>
);
};
const UserComponent = () => {
const { emit } = useEvents();
const handleLogin = (user: User) => {
emit("userLoggedIn", user);
};
const handleLogout = () => {
emit("userLoggedOut");
};
return (
<>
<button onClick={() => handleLogin({ name: "John Doe" })}>Login</button>
<button onClick={handleLogout}>Logout</button>
</>
);
};
const { createEventContext, createEventHook, createEventProvider } =
factory<AppEvents>();
createEventContext
: A function that creates the context for the event emitter.
createEventHook
: A function that creates a hook for the event emitter.
createEventProvider
: A function that creates a provider for the event emitter.
factory
: A factory function that returns the createEventContext, createEventHook, and
createEventProvider functions with the specified events passed as a generic type.
const { subscribe, emit } = useEvents();
subscribe
: A function for subscribing to an event. it takes the event name and a callback function as arguments. It will return a callback to unsubscribe from the event.
emit
: A function that emits an event. It takes the event name and as a second argument the payload matching the type of the context.
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
Distributed under the MIT License. See LICENSE.txt
for more information.
Project Link: https://github.com/julianfere/hooked