0.1.2 • Published 7 months ago

use-static-callback v0.1.2

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
7 months ago

useStaticCallback

An alternative to useCallback that don't require a dependencies list to stay up-to-date.

npm npm bundle size

// 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} /><>;
}
0.1.2

7 months ago

0.1.1

7 months ago

0.1.0

7 months ago