@tomisin.dev/use-cached-callback
v1.0.1
Published
A custom React hook that enhances useCallback by caching results based on the function's inputs.
Readme
useCachedCallback
A custom React hook that enhances useCallback by caching results based on the function's inputs. If the hook is called with the same arguments as before, it returns the cached result instead of recalculating it.
Installation
You can install this package via npm or yarn.
npm
npm install @tomisin.dev/use-cached-callbackyarn
yarn add @tomisin.dev/use-cached-callbackUsage
Below is a simple example of how to use useCachedCallback in your React component:
import React from 'react';
import { useCachedCallback } from '@tomisin.dev/use-cached-callback';
function expensiveCalculation(a: number, b: number): number {
// Imagine a heavy calculation here
return a + b;
}
export default function MyComponent() {
// Wrap the expensiveCalculation function with useCachedCallback
const cachedCalculation = useCachedCallback(expensiveCalculation, []);
const handleClick = () => {
// Calling with the same inputs will return the cached result
const result = cachedCalculation(1, 2);
console.log('Result:', result);
};
return (
<div>
<button onClick={handleClick}>Calculate</button>
</div>
);
}API
useCachedCallback
function useCachedCallback<T extends (...args: any[]) => any>(
callback: T,
deps: any[]
): T;- Parameters:
callback: The function whose result you want to cache.deps: Dependency array to determine when to refresh the cached callback.
- Returns:
A memoized function that caches its output based on the JSON-stringified representation of its arguments.
How It Works
Caching Mechanism:
The hook uses aMapstored in a ref to keep track of previous results. It generates a cache key by JSON-stringifying the function's arguments.Cache Retrieval:
When the returned function is called, it first checks if the cache contains the result for the given arguments. If it does, that cached value is returned immediately.Cache Update:
If there’s no cached result, the hook calls the original function, caches the output, and then returns the new result.
Contributing
Contributions, bug reports, and feature requests are welcome! Please open an issue or submit a pull request on the repository.
License
This project is licensed under the MIT License.
