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
You can use the
useLocation()
hook fromreact-router-dom
to get the current location object and pass it as a dependency to theuseEffect()
hook in the App component.You can wrap your App component in index.js instead of in the App component. For example:
Use
react-router-dom
‘suseLocation
withuseEffect
. ImportuseLocation
fromreact-router-dom
and embed it in auseEffect
block like below :