React Js Detect user switches tabs or leaves the page
React Js Detect user switches tabs or leaves the page:In React.js, you can detect when a user switches tabs or leaves the page by utilizing the
visibilitychange
event provided by the Document Object Model (DOM). By attaching an event listener to the visibilitychange
event, you can trigger specific actions when the visibility state changes. For example, you can pause or stop ongoing processes, display a warning message, or save the user's progress.This event is fired when the user switches tabs, minimizes the window, or switches to a different application. Handling this event effectively allows you to provide a better user experience and maintain application state accordingly.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
How can React.js detect when a user switches tabs or leaves the page?
The provided code demonstrates how to detect if a user switches tabs or leaves the page in a React.js application. It utilizes the useEffect
hook to add an event listener for the visibilitychange
event. When the event is triggered and the document becomes hidden (document.hidden
is true
), the message state is updated to "Goodbye, world!" indicating that the user has switched tabs or left the page. When the user comes back to the page, the message state is updated to "Welcome back!"
React Js Detect user switches tabs or leaves the page Example
Copied to Clipboard
xxxxxxxxxx
<script type="text/babel">
const { useState, useEffect } = React;
function App() {
const [message, setMessage] = useState('https://fontawesomicons.com');
useEffect(() => {
const handleVisibilityChange = () => {
if (document.hidden) {
// User switched tabs or left the page
setMessage('Goodbye, world!');
} else {
// User came back to the page
setMessage('Welcome back!');
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
return (
<div className='container'>
<h3>React Js Detect user switches tabs or leaves the page</h3>
<p>{message}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
Output of React Js Detect user switches tabs or leaves the page
Before Leave Page
After Leave Page
Ad