Skip to content
jshacks.dev
Frameworks

Subscribe to an external store with useSyncExternalStore

Read a value that lives outside React, such as navigator.onLine, with useSyncExternalStore so renders stay consistent and the server can render too.

1 min read
Summarize in AI

Browser state like network status changes outside React. Copying it into state with an effect can show a stale value for a render, while useSyncExternalStore reads it safely during render.

src/useOnlineStatus.jsJSX
import { useSyncExternalStore } from 'react';

function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

export function useOnlineStatus() {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine,
    () => true,
  );
}
src/StatusBar.jsxJSX
import { useOnlineStatus } from './useOnlineStatus.js';

export function StatusBar() {
  const isOnline = useOnlineStatus();
  return <p>{isOnline ? '✅ Online' : '❌ Disconnected'}</p>;
}
Text
✅ Online          (connected)
❌ Disconnected    (after the browser fires "offline")

The three arguments are how to subscribe, how to read the current value in the browser, and what to assume on the server. React calls the snapshot function on every render and compares with Object.is, so it must return the same value when nothing changed. A fresh object each time causes an infinite loop. See useSyncExternalStore.

For state that lives in React, useState is the right tool, not this hook.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.