Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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(() => {
}, [url]);
export default useNavigateTo;

This comment has been minimized.

Copy link
Owner Author

@bjgrosse bjgrosse commented Jan 22, 2020

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
You can’t perform that action at this time.