Lifting state up and Context

As apps grow, several components need the same data. A cart badge in the header and an "Add to cart" button deep in a product page both care about the cart. React offers two tools for sharing state: lifting state up and Context.

Lifting state up

When two siblings need the same state, move it to their closest common parent and pass it down as props:

Both inputs stay in sync because there's one piece of state, owned by the parent.

The problem: prop drilling

When the data is needed deep down, you end up passing props through components that don't use them:

App (user) → Layout (user) → Sidebar (user) → Menu (user) → Avatar (user)   😫

Context: broadcast a value to a whole subtree

In React 19 you can render <ThemeContext value={…}> directly. Older code uses <ThemeContext.Provider value={…}>, which still works.

A real pattern: a cart provider with a custom hook

Put the state and the functions that update it in one provider, and expose a hook:

Header, ProductList and ClearButton share the cart without passing any props.

When to use Context

✓ Good for app-wide, slowly changing data: the current user, theme, language, feature flags, and the cart in small apps.

✗ Avoid it for rapidly changing data used in many places. Every consumer re-renders when the value changes. For complex global state, teams often reach for Zustand, Redux Toolkit or Jotai, and for server data, TanStack Query.

Start simple: local state → lift it up → Context → a state library. Only move to the next step when you feel real pain.

Practice: language switcher

Create a LanguageContext with 'en' and 'hi', and a t(key) function that returns a translation from a dictionary like { en: { hello: 'Hello' }, hi: { hello: 'नमस्ते' } }. Build a LanguageProvider, a useLanguage() hook, a switcher button, and two components that display translated text.

React · live preview
Preview
✎ Check your understanding

1.Two sibling components need the same state. What's the first thing to try?

2.What problem does Context solve?