Labs ICT
โญ Pro Login

useContext Hook

Accessing context without prop drilling.

What is Context?

Context is React's way of passing data down the component tree without manually passing props at every level. Imagine you have a theme preference that needs to be accessible deep in your component tree. Without context, you'd have to pass it through every single parent component - that's called "prop drilling" and it's a nightmare. Context lets you provide data to any component that needs it, no matter how deeply nested it is.

Think of context like a broadcast radio station. Instead of handing someone a physical radio (prop drilling), you broadcast on a frequency, and anyone who tunes in gets the signal. The provider sets the frequency, and consumers tune in to receive the data.

Creating and Providing Context

To create context, you use React.createContext and wrap your component tree with a Provider. The Provider component has a value prop that holds whatever data you want to make available. Any component inside that Provider can access the value, no matter how deep it is in the tree.

const ThemeContext = React.createContext("light")
function App() {
  const [theme, setTheme] = useState("light")
  return (
    <ThemeContext.Provider value={theme}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  )
}
Try it Yourself โ†’

Consuming Context with useContext

The useContext Hook is the modern way to consume context. Just pass the context object you created, and it returns the current value. No more render props or nested consumers needed. It's clean, simple, and gets the job done. The component using useContext will re-render whenever the context value changes.

function ThemedButton() {
  const theme = useContext(ThemeContext)
  return (
    <button className={theme === "dark" ? "dark-btn" : "light-btn"}>
      Click me
    </button>
  )
}
Try it Yourself โ†’

Context vs Props

So when should you use context instead of props? Use props when data needs to be passed to specific, known components. Use context when data needs to be available to many components at different nesting levels, or when you want to avoid prop drilling. Common candidates for context include themes, authentication status, language preferences, and any global app state.

Don't go overboard with context though. It's not a replacement for all prop passing. Props are explicit and make component APIs clear. Context is best for truly global or deeply nested data that many components need. Overusing context can make your app harder to debug because data flow becomes implicit.

๐Ÿงช Quick Quiz

What does useContext do?