Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Last active Jan 14, 2020
Embed
What would you like to do?
blog5.md
// Solution 1
function useFunctionHook(fn, countInParent) {
  const [count, setCount] = React.useState(0);
  const fnRef = React.useRef(null)
  React.useEffect(() => {
    fnRef.current = 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