Skip to content

Instantly share code, notes, and snippets.

@erming
Created July 13, 2025 13:55
Show Gist options
  • Select an option

  • Save erming/6c04fa14ea8796ddf283b35b5c526e24 to your computer and use it in GitHub Desktop.

Select an option

Save erming/6c04fa14ea8796ddf283b35b5c526e24 to your computer and use it in GitHub Desktop.
useModel.js
import _ from "lodash";
import { useState, useLayoutEffect, useMemo } from "preact/hooks";
export const useModel = (origin) => {
const [model, setModel] = useState(origin);
function reset() {
setModel(_.cloneDeep(origin));
}
useLayoutEffect(() => {
if (origin) {
reset();
}
}, [JSON.stringify(origin)]);
const hasChanged = useMemo(() => {
return !_.isEqual(JSON.stringify(model), JSON.stringify(origin));
}, [model]);
return [
model,
(state) => {
setModel({
...model,
...state,
});
},
hasChanged,
reset
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment