@applicaster/zapp-react-native-ui-components
Version:
Applicaster Zapp React Native ui components for the Quick Brick App
51 lines (42 loc) • 1.23 kB
text/typescript
import { create, useStore } from "zustand";
import { produce } from "immer";
import { useCallback, useMemo } from "react";
type Dimensions = {
width: Option<number>;
height: Option<number>;
};
type DimensionsState = {
dimensions: Record<string, Dimensions>;
setCachedDimensions: (id: string, dimensions: Dimensions) => void;
};
const dimensionsStore = create<DimensionsState>((set) => ({
dimensions: {},
setCachedDimensions: (id, dimensions) =>
set(
produce((draft) => {
draft.dimensions[id] = dimensions;
})
),
}));
const initialDimensions = () => ({
width: undefined,
height: undefined,
});
export const useCachedDimensions = (id: string) => {
const { dimensions, setCachedDimensions } = useStore(
dimensionsStore
) as DimensionsState;
const getCachedDimensions = useCallback(() => {
return dimensions[id] || initialDimensions();
}, [dimensions?.[id], id]);
const handleSetCachedDimensions = useCallback((newDimensions) => {
setCachedDimensions(id, newDimensions);
}, []);
return useMemo(
() => ({
getCachedDimensions,
setCachedDimensions: handleSetCachedDimensions,
}),
[getCachedDimensions, handleSetCachedDimensions]
);
};