Created
July 13, 2025 13:55
-
-
Save erming/6c04fa14ea8796ddf283b35b5c526e24 to your computer and use it in GitHub Desktop.
useModel.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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