useSyncExternalStore Mini Store
ReactJS
Hard
6 views
Problem Description
Subscribe to an external store without tearing using useSyncExternalStore.
Output Format
Render a React component.
Constraints
Build a tiny store with subscribe/getSnapshot/setState.
Official Solution
import React, { useSyncExternalStore } from 'react';
function createStore(initial) {
let state = initial;
const listeners = new Set();
return {
getSnapshot() {
return state;
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
setState(next) {
state = typeof next === 'function' ? next(state) : next;
listeners.forEach((l) => l());
}
};
}
const store = createStore({ count: 0 });
function useStore(selector) {
const snap = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
return selector(snap);
}
export default function App() {
const count = useStore((s) => s.count);
return (
<div style={{ padding: 16, width: 420 }}>
<h2 style={{ marginTop: 0 }}>meetcode store</h2>
<div style={{ fontSize: 28, fontWeight: 900 }}>{count}</div>
<div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
<button type='button' onClick={() => store.setState((s) => ({ ...s, count: s.count + 1 }))} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>+1</button>
<button type='button' onClick={() => store.setState({ count: 0 })} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Reset</button>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!