react.dev
react.dev copied to clipboard
`useSyncExternalStore` Usage example question
trafficstars
Question Link
https://react.dev/reference/react/useSyncExternalStore#subscribing-to-a-browser-api
Summary
Hello!
I have a question about usage of useSyncExternalStore example
in this example, you can check navigator.onLine status using useSyncExternalStore.
Yeah, example works well, but i have one more question.
you can also implement this feature using useEffect https://codesandbox.io/s/magical-http-qrpjss?file=/src/App.js:24-627
import { useEffect, useState } from "react";
export default function App() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
useEffect(() => {
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return <h1>{isOnline ? "✅ Online" : "❌ Disconnected"}</h1>;
}
It also works.
if window event can fire some action, we can implement same feature using setState without useSyncExternalStore so i need more explanation that why we use useSyncExternalStore in this situation.
it`s my sheer of curiosity.
can you explain more reason or example about this case?
Thank you!!