๐ "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);
}
๐ก 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)