Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Last active January 14, 2020 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simbathesailor/f9e9a420290b28b4b36b1ed63722494c to your computer and use it in GitHub Desktop.
Save simbathesailor/f9e9a420290b28b4b36b1ed63722494c to your computer and use it in GitHub Desktop.
blog7.md
// Solution 1
function useFunctionHook(fn, countInParent) {
  const [count, setCount] = React.useState(0);
  const [fnRef] = useRefValues(fn)
  React.useEffect(
    () => {
     
      fnRef.current();
    },
    [count, setCount, fnRef, countInParent] 
 // here we have made fnRef kind of silent. 
 // It will never change after first run of the hook. as we are not changing
 // the cover
       
  );
  return [setCount, fnRef.current];
}

function App() {
  const [countInParent, setCountInParent] = React.useState(0);
  function fn() {
    console.log("Hi bro");
  }
  

  const [setCount] = useFunctionHook(fn, countInParent);

  return (
    <div>
      <button
        style={{ marginTop: "50px" }}
        onClick={() => setCountInParent(countInParent + 1)}
      >
        <h1>{countInParent}</h1>
        Change Count
      </button>
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment