0

Let's say there is a website with routes: /routeA, /routeB ... /routeZ

Each of those routes render a ComponentA, ComponentB ... ComponentZ

How to run a particular piece of code no matter which route has been reached?

The piece of code is irrelevant. It could be console.log("Awesome stackoverflow")

Obviously, in each component I could call useEffect and call the piece of code there. However, this is repetitive since I would have to write Z useEffect for the Z components we have. Instead, I am looking for a way to execute the piece of code without needing to repeate code through all components.

5
  • route is reaching inside some component, for example App, so in useEffect or ComponentDidMount you can run any code you like Commented May 30, 2020 at 15:13
  • or please specify what this code should do Commented May 30, 2020 at 15:14
  • Hi Dmitry. Thank you. I am looking for a way to execute the code without calling it from the components. I updated the question. Commented May 30, 2020 at 15:50
  • yes, but answer is the same - no need to call it inside route component, call it in their parent component Commented May 30, 2020 at 15:52
  • it is a nice case for hoc @fjplaurr Commented May 30, 2020 at 15:54

2 Answers 2

2

You can use the useLocation hook that is a part of react-use I can confirm this bit of code works using react-router, and this useEffect has to reside in the same component with your <Router> component, for me this was App.js

 const location = useLocation();

  useEffect(() => {
    // code to run on every route
  }, [location]);
Sign up to request clarification or add additional context in comments.

Comments

1
//if you are using class
class YourComponent extends React.Component{
    componentDidMount = () => {
        //your logic here
    }
}

//if you are using hook
const YourComponent = () => {
    useEffect(() => {
       //your logic here
    },[])
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.