Skip to content

Commit 5d2188a

Browse files
committed
fix(overmind-react): improve createHook with idomatic usage of useEffect
1 parent 0672ab8 commit 5d2188a

File tree

1 file changed

+27
-34
lines changed
  • packages/node_modules/overmind-react/src

1 file changed

+27
-34
lines changed

packages/node_modules/overmind-react/src/index.ts

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -50,53 +50,46 @@ export const createHook = <A extends Overmind<Configuration>>(overmind: A) => {
5050
typeof component.__componentId === 'undefined'
5151
? nextComponentId++
5252
: component.__componentId
53-
const trackId = overmind.trackState()
54-
const [overmindState, setOvermindState] = useState(() => {
55-
const paths = overmind.clearTrackState(trackId)
56-
componentInstanceId++
53+
const [thisComponentInstanceId] = useState(() => componentInstanceId++)
54+
const [_, forceUpdate] = useState(null)
55+
56+
useEffect(() => {
5757
overmind.eventHub.emitAsync(EventType.COMPONENT_ADD, {
5858
componentId: component.__componentId,
59-
componentInstanceId,
59+
componentInstanceId: thisComponentInstanceId,
6060
name,
61-
paths: Array.from(paths),
61+
paths: [],
6262
})
63-
return {
64-
componentInstanceId,
65-
listener: overmind.addFlushListener(paths, (flushId) => {
63+
return () => {
64+
overmind.eventHub.emitAsync(EventType.COMPONENT_REMOVE, {
65+
componentId: component.__componentId,
66+
componentInstanceId: thisComponentInstanceId,
67+
name,
68+
})
69+
}
70+
}, [])
71+
72+
const trackId = overmind.trackState()
73+
74+
useEffect(() => {
75+
const paths = overmind.clearTrackState(trackId)
76+
77+
if (paths) {
78+
const listener = overmind.addFlushListener(paths, (flushId) => {
79+
forceUpdate(flushId)
6680
overmind.eventHub.emitAsync(EventType.COMPONENT_UPDATE, {
6781
componentId: component.__componentId,
68-
componentInstanceId,
82+
componentInstanceId: thisComponentInstanceId,
6983
name,
7084
flushId,
7185
paths: Array.from(paths),
7286
})
73-
setOvermindState((state) => state)
74-
}),
75-
}
76-
})
77-
78-
useEffect(() => {
79-
const paths = overmind.clearTrackState(trackId)
80-
if (paths) {
81-
overmind.eventHub.emitAsync(EventType.COMPONENT_UPDATE, {
82-
componentId: component.__componentId,
83-
componentInstanceId: overmindState.componentInstanceId,
84-
name,
85-
paths: Array.from(paths),
8687
})
87-
overmindState.listener.update(paths)
88+
return () => {
89+
listener.dispose()
90+
}
8891
}
8992
})
90-
useEffect(() => {
91-
return () => {
92-
overmind.eventHub.emitAsync(EventType.COMPONENT_REMOVE, {
93-
componentId: component.__componentId,
94-
componentInstanceId: overmindState.componentInstanceId,
95-
name,
96-
})
97-
overmindState.listener.dispose()
98-
}
99-
}, [])
10093

10194
return overmind
10295
}

0 commit comments

Comments
 (0)