diff --git a/country-explorer/src/hooks/useFavorites.ts b/country-explorer/src/hooks/useFavorites.ts new file mode 100644 index 0000000..1064245 --- /dev/null +++ b/country-explorer/src/hooks/useFavorites.ts @@ -0,0 +1,31 @@ +import { useCallback, useState } from 'react'; + +/** + * Tracks which countries the user has marked as favorites, identified by + * their stable country code (the alpha-3 code already used as `Country.code` + * everywhere else in the app). + * + * This only holds the in-memory React state — persisting favorites to + * localStorage is handled separately. + */ +export function useFavorites() { + const [favoriteCodes, setFavoriteCodes] = useState([]); + + const addFavorite = useCallback((code: string) => { + // Guard against duplicates instead of relying on callers to check first. + setFavoriteCodes((current) => (current.includes(code) ? current : [...current, code])); + }, []); + + const removeFavorite = useCallback((code: string) => { + setFavoriteCodes((current) => current.filter((favoriteCode) => favoriteCode !== code)); + }, []); + + const isFavorite = useCallback((code: string) => favoriteCodes.includes(code), [favoriteCodes]); + + return { + favoriteCodes, + addFavorite, + removeFavorite, + isFavorite, + }; +}