Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Last active December 25, 2019 08:31
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/384244f57d55d3be401b129fcf1ed208 to your computer and use it in GitHub Desktop.
Save simbathesailor/384244f57d55d3be401b129fcf1ed208 to your computer and use it in GitHub Desktop.
Function reference changes on re-render
function useFunctionHook(fn) {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    // some logic
    // if fn changes the hooks callback will run
  }, [count, setCount, fn]);
  return [setCount, fn];
}
// Moved the fn out , now fn will have the same reference across re-render
function fn() {
    // some logic
}

function App() {
  const [countInParent, setCountInParent] = React.useState(0);

  const [setCount] = useFunctionHook(fn);
return (
    <div>
      some child component inside.
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment