From e8528ca5ff710d0651968b4f3f54f5d5aedbb8ed Mon Sep 17 00:00:00 2001 From: Sawaymaan Singh Date: Tue, 15 Sep 2026 02:27:52 +0200 Subject: [PATCH] feat: implement favorites state Add a useFavorites hook that tracks favorite country codes with add/remove functions and duplicate protection. Closes #31 --- country-explorer/src/hooks/useFavorites.ts | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 country-explorer/src/hooks/useFavorites.ts 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, + }; +}