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)