Phase 7: Set Favorite Fruit

Understand the Problem

We want to give users the ability to choose their favorite fruit from a dropdown. Once selected, the choice should update the app-wide context. We’ll need a controlled select input tied to the context value, and a function to update it when changed.

Devise a Plan

  1. Access the current favorite fruit ID and setter from context
  2. Render a <select> dropdown with all fruits
  3. Set the selected option using the current context value
  4. Update the context value when the dropdown changes

Carry Out the Plan

File: src/SetFavoriteFruit.jsx

// Pseudocode:
// 1. Access favFruitId and setFavFruitId from context
// 2. Render dropdown with fruit options
// 3. When changed, call setFavFruitId with the new ID

import { useContext } from 'react';
import { FavFruitContext } from '../context/FavFruitContext';

function SetFavoriteFruit({ fruits }) {
  const { favFruitId, setFavFruitId } = useContext(FavFruitContext);

  return (
    <div className="set-fav-fruit">
      <h2>Select your Favorite Fruit</h2>
      <label>
        <select value={favFruitId} onChange={e => setFavFruitId(e.target.value)}>
          {fruits.map(fruit => (
            <option key={fruit.id} value={fruit.id}>
              {fruit.name}
            </option>
          ))}
        </select>
      </label>
    </div>
  );
}

export default SetFavoriteFruit;

Expected Input and Output

Explanation for New Developers

This is an example of using a controlled component with shared state. The dropdown’s value is tied to the app’s context. When the user picks something new, we use setFavFruitId to update it across the entire app.

This ensures the rest of the app knows which fruit is currently the user's favorite, including the FavoriteFruit component.

Real World Analogy

This is like setting your favorite music genre in a profile settings menu. Once selected, the app updates everywhere to reflect your preference. This dropdown works the same way — it's the user's settings control panel.

Bonus Tip

You can use localStorage to persist this value across page refreshes or sessions for a more advanced experience.