Codstak
    • Home
    • DSA
    • JavaScript
    • TypeScript
    • Node.js
    • React
    • More↓
      BlogReact PrepPricingDiscordNewsletterLeaderboard
    React challenge/easy

    Shared Greeting Context

    Challenge workspace

    20-25 min
    Component compositionPath 30/40
    Components & propsCompositionState & events

    Suggested first

    Repair Account Settings Tabs

    Your workspace must pass its server-side browser checks to complete this challenge.

    Shared Greeting Context

    NavBar and WelcomeBanner both need the current user's name but they are in separate branches of the component tree. Wire a context so neither component needs the name passed as a prop.

    Requirements

    • Call createContext<{ name: string }> to create UserContext.
    • Create UserProvider — a component that wraps its children in UserContext.Provider with value={{ name: "Sam" }}.
    • In NavBar and WelcomeBanner, call useContext(UserContext) to read the name.
    • Wrap the root layout in <UserProvider> inside App.

    What to explain

    What problem does context solve that props can't? When would you choose a prop instead?

    Progressive hints

    1. createContext(defaultValue) returns an object; import and call it at module level.
    2. <UserContext.Provider value={...}> makes the value available to all descendants.
    3. const { name } = useContext(UserContext) reads the nearest provider's value in any child component.