Skip to content

Commit

Permalink
feat: optimize normal store setState mechanism 🎢 (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
willnguyen1312 authored May 16, 2023
1 parent 32a1ea9 commit 2768637
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/eleven-spiders-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zoom-image/core": minor
---

optimize normal store setState mechanism 🎢
5 changes: 5 additions & 0 deletions .changeset/good-dogs-think.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zoom-image/core": minor
---

Optimize rendering mechanism 🚀
18 changes: 8 additions & 10 deletions packages/core/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export function createStore<TState>(initialState: TState) {
let prevState: TState | undefined

const setState = (updatedState: Partial<TState>) => {
if (batching && !prevState) {
if (!prevState) {
prevState = { ...state }
}

Expand All @@ -20,16 +20,14 @@ export function createStore<TState>(initialState: TState) {
const flush = () => {
if (batching) return

if (!prevState) {
listeners.forEach((listener) => listener(state))
return
}

let hasChanged = false
for (const key in state) {
if (state[key] !== prevState[key]) {
hasChanged = true
break

if (prevState) {
for (const key in state) {
if (state[key] !== prevState[key]) {
hasChanged = true
break
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions packages/core/test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ describe("simple store", () => {
expect(listener1).toHaveBeenCalledTimes(1)
expect(listener2).toHaveBeenCalledTimes(1)

store.setState({ count: 1 })
store.setState({ count: 1 })
store.setState({ count: 1 })
expect(listener1).toHaveBeenCalledTimes(1)
expect(listener2).toHaveBeenCalledTimes(1)

unsubscribe()
store.setState({ count: 2 })
expect(store.getState()).toEqual({ count: 2 })
Expand Down

0 comments on commit 2768637

Please sign in to comment.