0.1.0 • Published 2 years ago

kill-use-callback v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

kill-use-callback

npm npm bundle size npm type definitions GitHub

This package provides memorized callbacks (like useCallback) for any callbacks like it's inline or in a condition or loop.

Please ⭐ star this repo if it's useful!

import React from "react";
import { propsAreEqual, depFn, useEffect } from "./kill-use-callback";

const Child = React.memo(
  ({getText}) => <div>{getText()}</div>,
  propsAreEqual);

export default function App({items}) {
  const [text, setText] = React.useState("a");
  const [text2, setText2] = React.useState("b");

  const getText = depFn((prefix) => `${prefix}: ${text}`, [text]);
  useEffect(() => {
    console.log(getText("Effect"));
  }, [getText]);

  return (
    <div>
      {items.map(item => (
        <Child getText={depFn(() => `${item}: ${text}`, [text])} />
      ))}
    </div>
  );
}

When text2 changes, Child won't re-render and the effect won't re-trigger.
And text changes, Child will re-render and the effect will re-trigger.

Demo

Please check this codesandbox example.