External store synchronization

외부 저장소 동기화

Subscribe to a store outside React and render a consistent snapshot.

···
html
<div class="scene"><div class="views"><div class="view">VIEW A<b id="a">0</b></div><div class="store">STORE<b id="store">0</b></div><div class="view">VIEW B<b id="b">0</b></div></div><div class="links"><span></span><span></span></div><div class="label" id="note">one snapshot, two subscribers</div></div>
css
.scene{width:min(94vw,800px);height:min(86vh,320px);position:relative;overflow:hidden;display:flex;flex-direction:column;justify-content:space-between;border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(9px,2.4vmin,20px);font:500 clamp(15px,4vmin,18px)/1.3 var(--font-sans,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}.scene b,.scene strong{font-weight:700}.label{color:var(--muted)}.code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.pill{border:1px solid var(--line);border-radius:8px;padding:.4em .65em;background:var(--bg)}.active{border-color:var(--accent)!important;color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 10%,var(--surface))!important}.views{display:flex;align-items:center;justify-content:space-between;gap:5px;height:65%}.view,.store{width:30%;height:62%;border:1px solid var(--line);border-radius:8px;display:flex;align-items:center;justify-content:center;flex-direction:column}.store{border-color:var(--accent);color:var(--accent);background:var(--bg)}.views b{font:700 clamp(20px,6vmin,38px) ui-monospace,monospace}.links{display:flex;justify-content:space-around}.links span{width:30%;height:4px;background:var(--accent);border-radius:4px;animation:pulse 1.6s infinite alternate}@keyframes pulse{to{opacity:.2}}.label{text-align:center;margin-top:12px}
js
let n=0;function tick(){for(const id of ["a","b","store"])document.getElementById(id).textContent=n;document.getElementById("note").textContent="snapshot version "+n;n=(n+1)%5}tick();setInterval(tick,900)

useSyncExternalStore connects an external store to React through subscribe and getSnapshot functions. Several components may read the same snapshot.

In the demo, two views update together when the central store changes. getSnapshot should return the same reference while data is unchanged; a fresh object each call can cause repeated updates.

When to use

Use it to subscribe to browser APIs, shared state libraries, or caches outside React.

Open as page ↗