skip to Main Content

I’m writing a React app using react-router-dom for navigation. When using navigate(), I can see in devtools that the ‘root’ root component is being rendered. However, in the code snippet below, the console does not work, what is the reason for this?

function App() {
  useEffect(() => {
    console.log(123);
  });

  return (
    <Provider store={store}>
      <UserProvider>
        <RouterProvider router={router}/>
      </UserProvider>
    </Provider>
  );
}

2

Answers


  1. You can use the useLocation() hook from react-router-dom to get the current location object and pass it as a dependency to the useEffect() hook in the App component.

    import { useLocation } from "react-router-dom";
    
    const { pathname } = useLocation();
    
    useEffect(() => {
      console.log(123);
    }, [pathname]);
    

    You can wrap your App component in index.js instead of in the App component. For example:

    <Router>
        <App />
    </Router>
    
    Login or Signup to reply.
  2. Use react-router-dom‘s useLocation with useEffect. Import useLocation from react-router-dom and embed it in a useEffect block like below :

    import { useEffect} from 'react'
    import { useLocation } from "react-router-dom";
    
    const { pathname } = useLocation();
    
    useEffect(() => {
      console.log(pathname);
    }, [pathname]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search