AceDevHub
Beginner React Interview QuestionsBeginnerConcept

React · Question 31

What are Context and useContext in React?

Direct answer

Context lets a parent provide a value to descendants without manually passing that value through every intermediate component, and useContext reads and subscribes to it.

Theme.jsx
import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Save</button>;
}

Context is useful for values that are needed by many components at different depths, such as theme, locale, or authenticated-user information.