MyInternships.in

React Hooks

React useContext Hook

useContext reads the current value of a context from the nearest matching Provider above the component. It subscribes the component to that context, so it re-renders whenever the provided value changes.


What is useContext Hook in React?

useContext reads the current value of a context from the nearest matching Provider above the component. It subscribes the component to that context, so it re-renders whenever the provided value changes.

Why useContext Hook matters

It replaces the old Context.Consumer render-prop syntax with a single line, which keeps components flat and readable.

useContext Hook example

Old consumer syntax vs useContext
JSX
// Before
<ThemeContext.Consumer>
  {theme => <button className={theme}>Save</button>}
</ThemeContext.Consumer>

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

Key points to remember

  • It finds the closest Provider above it; with no provider it returns the createContext default.
  • Reading a context always subscribes the whole component — you cannot select one field out of it.
  • React 19 also allows <Context> directly as a provider, without .Provider.

Common mistakes with useContext Hook

  • Forgetting the Provider and silently getting the default value, often undefined.
  • Expecting to subscribe to only part of a context object — any change re-renders every consumer.

React useContext Hook— Interview Questions & FAQs

What happens if there is no Provider above useContext?+

It returns the default value passed to createContext. If that default is null or undefined you get confusing errors, which is why wrapping the read in a custom hook that throws a clear message is good practice.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships