Context in React — React Technical Interview Questions & Answers

Context in React

Context in React

  • Context skips prop drilling. createContext, wrap a tree in Provider value={…}, read with useContext in a child. Theme, current user, locale are classic. Don’t put fast-changing data (every keystroke of a form) in Context at the root — every consumer re-renders.
  • If only one child needs the value, pass a prop. Context is for ‘many deep children, rarely changes’ or ‘truly global concerns’.
  • Context in React — on screen: dark. Label did not get a theme prop. Provider sat above it.
  Provider value
      │
      ▼
  deep child
   useContext

Technical Interview Tip: When to use vs a prop. Re-render warning.

Code Examples for Context in React

Example

// Context
import { createContext, useContext } from "react";

const Theme = createContext("light");

function Label() {
  const theme = useContext(Theme);
  return <span>{theme}</span>;
}

export default function App() {
  return (
    <Theme.Provider value="dark">
      <Label />
    </Theme.Provider>
  );
}

Context in React — on screen: dark. Label did not get a theme prop. Provider sat above it.

How to Explain Context in React to an Interviewer

When is Context overkill?

One child away