A simple hook to replace useState (when using with Object type)
This file contains 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
/* | |
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