Skip to content

Commit

Permalink
fix: schedule store updates in rAFs
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed May 29, 2022
1 parent c49a800 commit d5bd024
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useBottomSheetMachine } from '..'
describe('useBottomSheetMachine', () => {
test('SET_MAX_HEIGHT', async () => {
function Printer() {
const { dispatch, state } = useBottomSheetMachine()
const { dispatch, state } = useBottomSheetMachine({ initialHeight: 614 })
useEffect(
() =>
void dispatch({
Expand Down
22 changes: 13 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ function createStore({
let snapshot = service.initialState
// transient is updated more frequently than the snapshot, outside of react render cycles
let transient = snapshot
let rAF = 0

return {
subscribe: (onStoreChange: () => void) => {
Expand All @@ -46,18 +47,21 @@ function createStore({
// @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)
// @TODO: put updateSnapshot actions in the state machine as declared events
// for now just re-render on every change and map out events in userland before abstracting them to the state machine
console.groupCollapsed('state.changed')
transient = state
console.log('transient', state.value, state.context)
if (state.changed) {
console.groupCollapsed('state.changed')
transient = snapshot = state
console.log(state.value, state.context)
onStoreChange()
console.groupEnd()
} else {
console.groupCollapsed('state.changed: false')
transient = state
console.log(state.value, state.context)
cancelAnimationFrame(rAF)
rAF = requestAnimationFrame(() => {
console.group('onStoreChange')
console.log({ value: state.value, context: state.context })
transient = snapshot = state
onStoreChange()
console.groupEnd()
})
console.groupEnd()
}
console.groupEnd()
})
console.debug('service.start')
service.start()
Expand Down

0 comments on commit d5bd024

Please sign in to comment.