Skip to content

Instantly share code, notes, and snippets.

@chasoft
Last active December 12, 2021 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chasoft/78fcf8d922afb825664898cd16c4bc84 to your computer and use it in GitHub Desktop.
Save chasoft/78fcf8d922afb825664898cd16c4bc84 to your computer and use it in GitHub Desktop.
A simple hook to replace useState (when using with Object type)
/*
URL: https://anh.pw/do-not-use-usestate-directly-when-working-with-nested-object
Note:
- v1.2: support update, toggle and delete
- v1.0: support update and toggle
*/
import { get, set, cloneDeep } from "lodash"
import { useDeepCompareEffect } from "react-use"
export default function useLocalComponentCache(_object = {}) {
const [cache, setCache] = useState(_object)
useDeepCompareEffect(() => {
setCache(_object)
}, [_object])
const handlers = React.useMemo(
() => ({
//option: isOneOf(["toggle", "delete"])
setLocalCache: (value, path, option) => {
if (!path)
setCache(value)
else
setCache(
(prevState) => {
let newCache = cloneDeep(prevState)
switch (option) {
case "toggle":
set(newCache, path, !get(prevState, path))
break
case "delete":
unset(newCache, path)
break
default:
set(newCache, path, value)
break
}
return newCache
}
)
}
}), [])
return {
localCache: cache,
handlers
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment