I am new to react.js. I have a simple page with table. When I reload the page, state is getting lost. Is there a way to detect the browser refresh ?
Asked
Active
Viewed 2.0k times
2
-
1Single page apps shouldn’t reload the whole page, just if you don’t want to hard-resets your state. – Kokodoko Nov 18 '17 at 17:23
-
2its not a single page app. – learning_vba Nov 18 '17 at 17:28
-
@learning_vba You don't need `renderTable();` in your `MainHandler.js` Because that'll be handled by `Dashboard.js` independently. – Hamza Baig Nov 18 '17 at 19:04
-
thing is I dont want to change the existing logic. Is there anyway to detect browser refresh? – learning_vba Nov 19 '17 at 00:42
3 Answers
5
The event beforeunload is executed just before window browser is being refreshed. Event is cancellable.
window.beforeunload = (e) => {
console.log('Stop this');
e.preventDefault()
e.returnValue = '';
};
When using React an option is to take control in your Application component, or your most higher order component, in the componentDidMount
lifecycle method as @georgim suggested instead componentWillUnmount
as I first suggested, and manage there what you want to achieve.
-
what do you think about componentDidMount in the top level component? (to detect reload) – Giorgi Moniava Jan 29 '19 at 12:46
-
@giorgim I have been trying it and besides it is better to use the `beforeunload` event listener, indeed it is more reliable to apply the logic in `componentDidMount`. – Dez Jan 31 '19 at 07:25
0
With [react-beforeunload][1] you can track the page changes easily
import { useBeforeunload } from 'react-beforeunload'
const App = () => {
const [preventMultiSubmit, setPreventMultiSubmit] = useState(false)
}
const pageRefConf = useBeforeunload((event) => {
if (preventMultiSubmit) {
event.preventDefault()
}
})
useEffect(() => {
window.addEventListener('beforeunload', pageRefConf)
return () => {
window.removeEventListener('beforeunload', pageRefConf)
}
}, [])
This worked for me. I hope this one will work for you too. [1]: https://www.npmjs.com/package/react-beforeunload

Roshith R
- 31
- 2
-1
Try this one. This worked for me.
if (window.performance) {
if (performance.navigation.type == 1) {
alert( "This page is reloaded" );
} else {
alert( "This page is not reloaded");
}
}

GunarathneMDD
- 180
- 1
- 2
- 11