Contaxt Api & Context Hook in React js 2025

Context API & useContext Hook in React JS 2025

The Context API in React is used to avoid props drilling and share state or functions between components without passing props manually at every level. It's ideal for global data like user info, theme, language, etc.

Steps to use Context API:

  • Create a Context using React.createContext()
  • Wrap components with Context.Provider
  • Access value using useContext() hook

React Example:


import React, { createContext, useContext, useState } from 'react';

// 1. Create Context
const ThemeContext = createContext();

// 2. Create Provider
function ThemeProvider({ children }) {
  const [darkMode, setDarkMode] = useState(false);
  return (
    
      {children}
    
  );
}

// 3. Use Context in Child
function ToggleButton() {
  const { darkMode, setDarkMode } = useContext(ThemeContext);
  return (
    
  );
}

// 4. Main App
function App() {
  return (
    
      
    
  );
}

export default App;

This approach allows you to manage global data in a clean and scalable way without passing props down manually through every component layer.