Hack Frontend Community
Practice React 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

import { createContext } from "react";

const ThemeContext = createContext("light");

Wrapping Components in Provider

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

Reading Data with useContext

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?

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

Theme Switching Example

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.