Creating a custom hook for handling online/offline status in a Next.js application involves using the useEffect
hook to add event listeners for online and offline events, and then updating the state accordingly. Here's a simple example:
jsximport { useState, useEffect } from 'react';
const useOnlineStatus = () => {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => {
setIsOnline(true);
};
const handleOffline = () => {
setIsOnline(false);
};
// Set up event listeners for online and offline events
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
// Clean up event listeners on component unmount
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []); // Empty dependency array ensures that the effect runs only once during component mount
return isOnline;
};
export default useOnlineStatus;
In this example:
useOnlineStatus
hook initializes the state (isOnline
) with the current online status using navigator.onLine
.useEffect
hook is used to set up event listeners for the online
and offline
events on the window
object.handleOnline
function is called, updating the state to true
.handleOffline
function is called, updating the state to false
.You can use this custom hook in your Next.js components like this:
jsximport React from 'react';
import useOnlineStatus from '../path-to-useOnlineStatus';
const MyComponent = () => {
const isOnline = useOnlineStatus();
return (
<div>
<p>Online Status: {isOnline ? 'Online' : 'Offline'}</p>
</div>
);
};
export default MyComponent;
Now, isOnline
will hold the current online/offline status, and your component will re-render whenever the online/offline status changes.