I expect that console.log('Refresh')
runs every time the route changes (switching from Component1 to Component2). But it's only triggering on first render. Why?
index.js
:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
App.js
:
import React, { useEffect } from 'react'; import { Switch, Route } from 'react-router-dom'; import Nav from './Nav'; import Component1 from './Component1'; import Component2 from './Component2'; const App = () => { useEffect( () => console.log('Refresh')); return ( [<Switch> <Route component = {Nav}/> </Switch>, <Switch> <Route exact path = '/component1' component = {Component1}/> <Route exact path = '/component2' component = {Component2}/> </Switch>] ); } export default App;
Nav.js
:
import React from 'react'; import { Link } from 'react-router-dom'; const Nav = () => { return ( <div> <Link to = '/component1'>Component 1</Link> <Link to = '/component2'>Component 2</Link> </div> ); } export default Nav;
Component1.js
:
import React from 'react'; const Component1 = () => { return ( <div> <p>Hi</p> </div> ); } export default Component1;
Component2.js
:
import React from 'react'; const Component2 = () => { return ( <div> <p>Bye</p> </div> ); } export default Component2;
Use the useEffect hook to listen for state changes in React. You can add the state variables you want to track to the hook's dependencies array and the logic in your useEffect hook will run every time the state variables change.
In this case, the side effect will run every time there is a change to the props passed as a dependency. useEffect(() => { // Side Effect }, [props]);
By default useEffect will trigger anytime an update happens to the React component. This means if the component receives new props from its parent component or even when you change the state locally, the effect will run again.
Important: the useEffect hook will always run on mount regardless of if there is anything in its dependency array.
The useEffect
is not triggered because the App
component is not re-rendered, nothing changed in that component (no state or props update).
If you want the App
component to re-render when the route change, you can use the withRouter
HOC to inject route props, like this :
import { Switch, Route, withRouter } from 'react-router-dom'; const App = () => { useEffect( () => console.log('Refresh')); return (...); } export default withRouter(App);
Example : https://codesandbox.io/s/youthful-pare-n8p1y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With