Medium
In a React application, you're building a custom hook to manage a shopping cart with local storage persistence. Which implementation correctly handles both cart updates and storage synchronization?
1function useShoppingCart() {2 const [cart, setCart] = useState(() => {3 try {4 const stored = localStorage.getItem('cart');5 return stored ? JSON.parse(stored) : [];6 } catch {7 return [];8 }9 });1011 _______________1213 const addItem = (product) => {14 setCart(currentCart => {15 const existingItem = currentCart.find(item => item.id === product.id);16 if (existingItem) {17 return currentCart.map(item =>18 item.id === product.id19 ? { ...item, quantity: item.quantity + 1 }20 : item21 );22 }23 return [...currentCart, { ...product, quantity: 1 }];24 });25 };2627 return { cart, addItem };28}