use-static-callback
v0.1.2
Published
An alternative to `useCallback` that don't require a `dependencies list` to stay up-to-date.
Downloads
13
Maintainers
Readme
useStaticCallback
An alternative to useCallback
that don't require a dependencies list
to stay up-to-date.
// Example
const [count, setCount] = useState(0);
const memoizedFn = useStaticCallback(() => {
setCount(count + 1); // up-to-date "count" value without the need of a dependencies array
});
Usage:
Preventing an Effect from firing too often.
Including a useCallback
function in a useEffect
dependencies list may cause the effect to fire too often. useStaticCallback
avoids this by returning a memoized function that will never change.
import { useEffect, useState } from "react";
import { useStaticCallback } from "use-static-callback";
function Items() {
const [items, setItems] = useState([]);
const fetchData = useStaticCallback(async () => {
const { json } = await fetch("fetch-items-url");
const newItems = await json();
setItems([...items, ..newItems]);
});
useEffect(() => {
fetchData();
}, [fetchData]); // "fetchData" will never change, so this Effect will only fire once.
return <>items: {items}</>;
}
Avoiding unwanted component re-rendering
If a useCallback
function is passed as a prop to a memoized component there is a chance it could trigger an unexpected re-render of the component. You can avoid this issue by using useStaticCallback
.
import { memo, useState } from "react";
import { useStaticCallback } from "use-static-callback";
const MemoizedField = memo(({ value, onChange }) => {
return <input value={value} onChange={onChange} />;
});
function Person() {
const [person, setPerson] = useState({ name: "", address: "" });
const onNameChange = useStaticCallback((e) => {
const newName = e.target.value;
setPerson({ ...person, name: newName });
});
// "onNameChange" will never change, so it can safely be passed as a prop to "MemoizedField" component.
return <>Name: <MemoizedField value={person.name} onChange={onNameChange} /><>;
}