Skip to content

Commit 5aeb08a

Browse files
Merge pull request cerebral#224 from FWeinb/react-refactor-ref
refactor(overmind-react): use useRef for storing componentId and tracking tree
2 parents 7664689 + 1f932c0 commit 5aeb08a

File tree

1 file changed

+17
-9
lines changed
  • packages/node_modules/overmind-react/src

1 file changed

+17
-9
lines changed

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

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
useEffect,
1212
// @ts-ignore
1313
useState,
14+
useRef,
1415
useLayoutEffect,
1516
createContext,
1617
useContext,
@@ -68,6 +69,13 @@ export const createHook = <Config extends Configuration>(
6869
? ReactCurrentOwner.current.elementType
6970
: {}
7071
}
72+
const useForceRerender = (): VoidFunction => {
73+
const [, setState] = useState(true)
74+
const forceRerender: VoidFunction = (): void => {
75+
setState((state) => !state)
76+
}
77+
return forceRerender
78+
}
7179

7280
return () => {
7381
const overmind = (overmindInstance || useContext(context)) as Overmind<
@@ -79,14 +87,14 @@ export const createHook = <Config extends Configuration>(
7987
typeof component.__componentId === 'undefined'
8088
? nextComponentId++
8189
: component.__componentId
82-
const [{ tree }, updateComponent] = useState<any>(() => ({
83-
tree: (overmind as any).proxyStateTree.getTrackStateTree(),
84-
}))
90+
91+
const rerenderComponent = useForceRerender()
92+
const { current: tree } = useRef<any>(
93+
(overmind as any).proxyStateTree.getTrackStateTree()
94+
)
8595

8696
if (IS_PRODUCTION) {
87-
tree.track(() => {
88-
updateComponent(({ tree }) => ({ tree }))
89-
})
97+
tree.track(rerenderComponent)
9098

9199
useEffect(
92100
() => () => {
@@ -97,12 +105,12 @@ export const createHook = <Config extends Configuration>(
97105

98106
useLayoutEffect(() => tree.stopTracking())
99107
} else {
100-
const [componentInstanceId] = useState<any>(
101-
() => currentComponentInstanceId++
108+
const { current: componentInstanceId } = useRef<any>(
109+
currentComponentInstanceId++
102110
)
103111

104112
tree.track((_, paths, flushId) => {
105-
updateComponent(({ tree }) => ({ tree }))
113+
rerenderComponent()
106114
overmind.eventHub.emitAsync(EventType.COMPONENT_UPDATE, {
107115
componentId: component.__componentId,
108116
componentInstanceId,

0 commit comments

Comments
 (0)