Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Created December 25, 2019 08:47
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/e837d57d107218049513e8ba22d179c9 to your computer and use it in GitHub Desktop.
Save simbathesailor/e837d57d107218049513e8ba22d179c9 to your computer and use it in GitHub Desktop.
useCallback approach for functions
function useFunctionHook(fn) {
  // now the fnCallback will only not change across rerender
  const fnCallback = React.useCallback(fn, [])
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    // some logic
    // if fnCallback changes the hooks callback will run
  }, [count, setCount, fnCallback]);
  return [setCount, fnCallback];
}

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

function fn() {
    // some logic
  }
  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