import * as React from "react"; import { useScreenContextV2 } from "@applicaster/zapp-react-native-utils/reactHooks/screen/useScreenContext"; import { useStore } from "zustand"; /** * A custom hook that provides persistent state storage across component re-mounts * using the screen's component state store. * * @see {@link DOCS/adr/0010-useComponentScreenState.md} - ADR explaining why useComponentScreenState is used for List/Hero/Grid/Gallery components * * The state is shared across all components using the same componentId within the same screen context. * If no value exists for the componentId, the initial value is returned as a fallback but is not persisted in the store. * The initial value must be explicitly set using the returned setter function to persist it. * * @template T - The type of value being stored * @param componentId - Unique identifier for this state in the component state store * @param initialValue - The default value if no value exists for the componentId * @returns A tuple containing the current value and a memoized setter function * * @example * ```tsx * const [count, setCount] = useComponentScreenState('counter', 0); * const [name, setName] = useComponentScreenState('username', 'Anonymous'); * ``` */ export const useComponentScreenState = ( componentId: string, initialValue: T ): [T, (value: T) => void] => { const store = useScreenContextV2()._componentStateStore; const value = useStore( store, (state) => (state[componentId] as T | undefined) ?? initialValue ); const setValue = React.useCallback( (nextValue: T) => { store.setState({ [componentId]: nextValue }); }, [componentId, store] ); return [value, setValue] as const; };