Skip to main content

What is Context in React?

Context in React is a mechanism that lets you pass data through the component tree, without using props at every level.


The problem Context solves

Normally, data in React flows top-down through props:

javascript
<App> <Header user={user} /> </App>

But if user is needed by a component deep inside the tree, you have to pass it through every intermediate component - this is called prop drilling. Context solves this problem.


How Context works

Context lets you create a global data store (at the level of React components) that any child component can connect to, without passing props manually.


Usage example

1. Create the context

javascript
import { createContext } from "react"; export const ThemeContext = createContext("light");

2. Wrap the components in a Provider

javascript
import { ThemeContext } from "./ThemeContext"; function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }

3. Subscribe to the context through useContext

javascript
import { useContext } from "react"; import { ThemeContext } from "./ThemeContext"; function Button() { const theme = useContext(ThemeContext); return <button className={theme}>Button</button>; }

Key elements

ElementPurpose
createContext(defaultValue)Creates a context with an initial value
<Context.Provider value={...}>Makes the value available to all child components
useContext(Context)Retrieves the current context value inside a component

Important to remember

  1. All components using the context will re-render if the value changes.
  2. To optimize, memoize value:
javascript
const value = useMemo(() => ({ user, setUser }), [user]); <UserContext.Provider value={value}>...</UserContext.Provider>
  1. Context does not replace global state managers (Redux, Zustand, etc.), but it fits well for:
  • UI theme (light/dark),
  • interface language,
  • the current user,
  • UI settings.

A simple comparison

ApproachWhen to use
propsLocal data passed 1-2 levels down
contextShared data needed in many places in the app
state managers (Redux, Zustand)Complex state with logic, side effects, caching, etc.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.