refactor(ui): useZustandShallowSelector
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import useBrowserTheme from "./useBrowserTheme";
|
||||
import useZustandShallowSelector from "./useZustandShallowSelector";
|
||||
|
||||
export { useBrowserTheme };
|
||||
export { useBrowserTheme, useZustandShallowSelector };
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useTheme } from "ahooks";
|
||||
|
||||
export default () => {
|
||||
export default function () {
|
||||
return useTheme({ localStorageKey: "certimate-ui-theme" });
|
||||
};
|
||||
}
|
||||
|
||||
18
ui/src/hooks/useZustandShallowSelector.ts
Normal file
18
ui/src/hooks/useZustandShallowSelector.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { pick, isArray } from "radash";
|
||||
|
||||
import { useRef } from "react";
|
||||
import { shallow } from "zustand/shallow";
|
||||
|
||||
type MaybeMany<T> = T | readonly T[];
|
||||
|
||||
export default function <T extends object, TKeys extends keyof T>(paths: MaybeMany<TKeys>): (state: T) => Pick<T, TKeys> {
|
||||
const prev = useRef<Pick<T, TKeys>>({} as Pick<T, TKeys>);
|
||||
|
||||
return (state: T) => {
|
||||
if (state) {
|
||||
const next = pick(state, isArray(paths) ? paths : [paths]);
|
||||
return shallow(prev.current, next) ? prev.current : (prev.current = next);
|
||||
}
|
||||
return prev.current;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user