Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Last active Jan 14, 2020
Embed
What would you like to do?
blog15.md
function useRefValues(value) {
  const ref = React.useRef(value);
  React.useEffect(() => {
    ref.current = value;
  });
  return [ref];
}


function useAcceptOptions(option, arr) {
  const { a, b, c, ...otherValues } = option;

  const { callback1, array1 } = otherValues;

  // usecallback takes second argument which make it more usable in most of the cases. The cases where we want
  // callbacks to change, but not every time. There is no such thing with useRef. Ofcourse we can simulate
  // that with the the help of some other hooks. But too much work

  const finalCallback = React.useCallback(callback1, [a, b]);
  const [refArr] = useRefValues(arr);
  // Here refArr is silent dependency
  React.useEffect(() => {
    console.log("some logic based on final callback");
  }, [a, b, c, finalCallback, refArr]);
}

function App() {
  // const [ref, setRef] = React.useRef(null) remove this
  const obj = {
    a: 1,
    b: 2,
    c: 3,
    callback1: aCallback
  };
  function aCallback() {
    console.log("hello a callback", obj.a, obj.b);
  }
  const arr = ["x", "y", "z"];

  useAcceptOptions(obj, arr);

  return <div>Hello World</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment