React useContext Hook

The useContext hook allows you to access React’s Context API more easily in functional components. Instead of manually wrapping components with a Consumer, useContext lets you consume the context directly, improving code readability and simplicity.


1 Basic Example for useContext Hook: Theme Context

In this example, we create a theme context to manage light and dark modes in an application. The useContext hook is used to retrieve the current theme.

</>
Copy
import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemeDisplay() {
  const theme = useContext(ThemeContext); // Access the current theme
  return <p>The current theme is: {theme}</p>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemeDisplay />
    </ThemeContext.Provider>
  );
}

export default App;

Explanation:

  • ThemeContext: A context created using createContext with a default value of 'light'.
  • useContext: Retrieves the current context value (in this case, 'dark').
  • The context value is set in the ThemeContext.Provider and consumed in the ThemeDisplay component.

Output: