Skip to content

Commit d5bd024

Browse files
committed
fix: schedule store updates in rAFs
1 parent c49a800 commit d5bd024

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

src/__tests__/index.test.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { useBottomSheetMachine } from '..'
66
describe('useBottomSheetMachine', () => {
77
test('SET_MAX_HEIGHT', async () => {
88
function Printer() {
9-
const { dispatch, state } = useBottomSheetMachine()
9+
const { dispatch, state } = useBottomSheetMachine({ initialHeight: 614 })
1010
useEffect(
1111
() =>
1212
void dispatch({

src/index.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ function createStore({
3838
let snapshot = service.initialState
3939
// transient is updated more frequently than the snapshot, outside of react render cycles
4040
let transient = snapshot
41+
let rAF = 0
4142

4243
return {
4344
subscribe: (onStoreChange: () => void) => {
@@ -46,18 +47,21 @@ function createStore({
4647
// @TODO: flesh out the logic for when to notify react of state changes or not (as state updates can be expensive and we should be transient when possible)
4748
// @TODO: put updateSnapshot actions in the state machine as declared events
4849
// for now just re-render on every change and map out events in userland before abstracting them to the state machine
50+
console.groupCollapsed('state.changed')
51+
transient = state
52+
console.log('transient', state.value, state.context)
4953
if (state.changed) {
50-
console.groupCollapsed('state.changed')
51-
transient = snapshot = state
52-
console.log(state.value, state.context)
53-
onStoreChange()
54-
console.groupEnd()
55-
} else {
56-
console.groupCollapsed('state.changed: false')
57-
transient = state
58-
console.log(state.value, state.context)
54+
cancelAnimationFrame(rAF)
55+
rAF = requestAnimationFrame(() => {
56+
console.group('onStoreChange')
57+
console.log({ value: state.value, context: state.context })
58+
transient = snapshot = state
59+
onStoreChange()
60+
console.groupEnd()
61+
})
5962
console.groupEnd()
6063
}
64+
console.groupEnd()
6165
})
6266
console.debug('service.start')
6367
service.start()

0 commit comments

Comments
 (0)