Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions country-explorer/src/hooks/useFavorites.ts
Original file line number Diff line number Diff line change
@@ -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<string[]>([]);

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,
};
}