reactjs / reactjs/react.dev

`useSyncExternalStore` Usage example question

Open
#6,442 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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!!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked React documentation entry for useSyncExternalStore, especially the “subscribing to a browser API” example, and compare it with the useEffect implementation in the issue. Done means the documentation clearly explains why the example uses useSyncExternalStore and when the alternative is appropriate.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.