React’s built-in way to share global-like state across deeply nested components without prop drilling.


createContext()

Creates a Context object with an optional default value.

const ThemeContext = createContext<'light' | 'dark'>('light');


<Context.Provider>

Provides the context value to all children in the tree.

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


useContext()

Reads the current context value from the nearest matching provider.

const theme = useContext(ThemeContext);


✅ Full Example

import { createContext, useContext } from 'react';

const UserContext = createContext<{ name: string } | null>(null);

function App() {
  return (
    <UserContext.Provider value={{ name: 'Merrick' }}>
      <Profile />
    </UserContext.Provider>
  );
}

function Profile() {
  const user = useContext(UserContext);
  return <p>Hello, {user?.name}</p>;
}


✅ Use Cases