Skip to content

useSyncExternalStore

vinibiavatti1 edited this page Sep 28, 2026 · 3 revisions

Subscribes to an external data store (such as state libraries or browser APIs like localStorage) and reads its current value. It guarantees synchronous, collision-free updates across concurrent rendering features in React. Requires two functions: subscribe (registers a callback when the store changes) and getSnapshot (returns the current value from the store).

import { useSyncExternalStore } from 'react';

// Registers a callback when the store changes
const subscribe = (callback) => {
    window.addEventListener('storage', callback);
    return () => window.removeEventListener('storage', callback);
}

// Returns the current value from the store
const getSnapshot = () => {
    return localStorage.getItem('theme') ?? 'light';
}

// Use the functions above to define an external store
export const MyComponent = () => {
    const theme = useSyncExternalStore(subscribe, getSnapshot);
};

Clone this wiki locally