Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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