Skip to main content
Practice Problems

What is context and useContext hook in React

Context in React is a way to pass data between components at any nesting level, bypassing manual prop passing (props) through each tree level.

Context is convenient when certain data (e.g., current user, language, theme) is needed in many components simultaneously.


Why Context?

  • Avoids prop drilling — necessity to pass data through multiple intermediate components.

  • Allows convenient work with global data:

  • Authorization

  • Theme (light / dark)

  • Localization

  • Application settings


Context API Usage Example

Creating Context

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

Wrapping Components in Provider

jsx
<ThemeContext.Provider value="dark"> <App /> </ThemeContext.Provider>

Reading Data with useContext

jsx
import { useContext } from "react"; function Header() { const theme = useContext(ThemeContext); return <h1 className={`header ${theme}`}>Hello!</h1>; }

Now Header component knows theme is "dark", without props!

useContext: how it works?

jsx
const value = useContext(ContextObject);
  • Allows getting current context value
  • Works only inside component wrapped in Context.Provider
  • Updates automatically when value in Provider changes

ThemeContext.Provider

Header Component

Sidebar Component

useContext Hook

Theme Switching Example

jsx
const ThemeContext = createContext("light"); function ThemeSwitcher() { const theme = useContext(ThemeContext); return <button className={`btn-${theme}`}>Switch theme</button>; }

When Not to Use Context

  • For frequently updated values (e.g., current input value)
  • When data can be passed directly through props (context = "heavy artillery")

Summary

  • Context is needed to conveniently share data between components without excessive prop passing.
  • useContext hook allows easy access to context value.
  • Suitable for theme, language, user settings, global state.

Tip:

Use context for data that's needed by many components and rarely changes.

Short Answer

Interview ready
Premium

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

Finished reading?
Practice Problems