Skip to content

Commit ac86fc9

Browse files
committed
create useStateRef hook internally
this avoids the need to constantly save the update hook since the original effect function holds onto a ref that will always be up to date. in the prior implementation there was some delay that was introduced (presumably due to triggering updates on stale callbacks).
1 parent e881dfa commit ac86fc9

File tree

2 files changed

+19
-21
lines changed

2 files changed

+19
-21
lines changed

Diff for: idom/client/app/core_modules/layout.js

+18-20
Original file line numberDiff line numberDiff line change
@@ -46,32 +46,20 @@ export function mountLayoutWithWebSocket(mountElement, endpoint) {
4646
}
4747

4848
export function mountLayout(mountElement, saveUpdateHook, sendEvent) {
49-
const updateHook = { current: null };
50-
51-
function setUpdateHook(hook) {
52-
updateHook.current = hook;
53-
}
54-
5549
reactDOM.render(
56-
html`<${Layout} setUpdateHook=${setUpdateHook} sendEvent=${sendEvent} />`,
50+
html`<${Layout} saveUpdateHook=${saveUpdateHook} sendEvent=${sendEvent} />`,
5751
mountElement
5852
);
59-
60-
saveUpdateHook((pathPrefix, patch) => {
61-
if (updateHook.current) {
62-
updateHook.current(pathPrefix, patch);
63-
}
64-
});
6553
}
6654

67-
export default function Layout({ setUpdateHook, sendEvent }) {
68-
const [model, setModel] = react.useState({});
55+
export default function Layout({ saveUpdateHook, sendEvent }) {
56+
const [modelRef, setModel] = useStateRef({});
6957

7058
react.useEffect(() => {
71-
setUpdateHook((pathPrefix, patch) => {
59+
saveUpdateHook((pathPrefix, patch) => {
7260
setModel(
7361
jsonpatch.applyPatch(
74-
model,
62+
modelRef.current,
7563
patch.map((op) => {
7664
op.path = pathPrefix + op.path;
7765
return op;
@@ -81,10 +69,13 @@ export default function Layout({ setUpdateHook, sendEvent }) {
8169
).newDocument
8270
);
8371
});
84-
}, [model]);
72+
}, [modelRef]);
8573

86-
if (model.tagName) {
87-
return html`<${Element} sendEvent=${sendEvent} model=${model} />`;
74+
if (modelRef.current.tagName) {
75+
return html`<${Element}
76+
sendEvent=${sendEvent}
77+
model=${modelRef.current}
78+
/>`;
8879
} else {
8980
return html`<div />`;
9081
}
@@ -212,3 +203,10 @@ function getPathProperty(obj, prop) {
212203
}
213204
return value;
214205
}
206+
207+
function useStateRef(initialValue) {
208+
const ref = react.useRef(initialValue);
209+
const [state, setState] = react.useState(initialValue);
210+
ref.current = state;
211+
return [ref, setState];
212+
}

Diff for: idom/client/app/package-lock.json

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)