Skip to content

Instantly share code, notes, and snippets.

@bjgrosse
Last active January 22, 2020 19:45
Show Gist options
  • Save bjgrosse/48fd06fedf80cb2b745837a71f1e6634 to your computer and use it in GitHub Desktop.
Save bjgrosse/48fd06fedf80cb2b745837a71f1e6634 to your computer and use it in GitHub Desktop.
React Router hook to navigate to a URL from inline event handler
import { useCallback } from "react";
import { useHistory } from "react-router-dom";
/**
* Uses history.push to navigate to the specified URL.
*
* @param {string} url
*
* Usage:
* <Button onClick={useNavigateTo("/start")}>Start</Button>
*/
const useNavigateTo = url => {
const history = useHistory();
return useCallback(() => {
history.push(url);
}, [url]);
};
export default useNavigateTo;
@bjgrosse
Copy link
Author

It was explained here that calling a hook inline from JSX is a bad practice because every hook used in a component must be executed on each render, and in the same order, otherwise the component will break. If another developer modifies the JSX to conditionally hide the Button, then the component will be broken.

See the react docs on hooks and the explanation there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment