What Is React Context API? Complete Example Tutorial Guide

What Is React Context API?

React Context API allows you to share data across components without passing props manually at every level.
It’s useful for themes, authentication, and global state.


Basic Syntax

const MyContext = React.createContext(defaultValue);
  • Provider → supplies the value
  • Consumer → reads the value

Example: Theme Context

import React, { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button style={{ background: theme === "dark" ? "#333" : "#ccc" }}>Click Me</button>;
}

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

export default App;

ThemedButton receives dark theme without prop drilling.


Key Points

  • Provides global state for a subtree
  • Avoids prop drilling
  • Works with useContext hook
  • Ideal for themes, auth, or settings

Conclusion

React Context API makes state sharing easy across components, simplifying global state management.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *