DEV Community

Aleksei Aleinikov
Aleksei Aleinikov

Posted on

๐Ÿ”ฅ How to Sync External Data in React 18 Without Breaking Your UI?

๐Ÿš€ "Just use useSyncExternalStore"โ€”they said... But why is my UI still breaking?!
If you've ever struggled with keeping state in sync with localStorage, global variables, or third-party sources, you're not alone. useSyncExternalStore, introduced in React 18, solves this problem elegantly.
๐Ÿ”น Why Not Just Use useState?
โœ… Prevents hydration errors in SSR
โœ… Ensures consistent state updates (no outdated UI parts)
โœ… Optimized for concurrent rendering in React 18+
๐Ÿ“Œ Example: Auto-Sync Username from localStorage

function getSnapshot() {
  return localStorage.getItem("userName") || "Anonymous";
}

function subscribeToStorage(callback) {
  function handleStorage(event) {
    if (event.key === "userName") callback();
  }
  window.addEventListener("storage", handleStorage);
  return () => window.removeEventListener("storage", handleStorage);
}

export function useUserNameFromStorage() {
  return React.useSyncExternalStore(subscribeToStorage, getSnapshot);
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Now your UI updates instantly when userName changes in another tab!
But that's just one example. Want to see how to use useSyncExternalStore for mouse tracking & SSR?
๐Ÿ“– Read the full breakdown โ†’ ๐Ÿ”— https://javascript.plainenglish.io/a-simple-way-to-sync-external-data-with-usesyncexternalstore-in-react-18-e7cb2b10e1d0
๐Ÿ’ฌ Have you tried useSyncExternalStore in production? Drop your thoughts below! ๐Ÿ‘‡

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay