How To Use useContext Hook In React? See Example

The useContext hook allows functional components to access context values directly.
It eliminates the need for Context.Consumer components.


Basic Syntax

const value = useContext(MyContext);
  • Returns the current context value
  • Must be used inside a component wrapped by the provider

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 accesses the context value directly with useContext.


Key Points

  • Simplifies context consumption in functional components
  • Works only within provider subtree
  • Avoids prop drilling
  • Works well with Context API for global state

Conclusion

useContext makes context usage easier and cleaner, enabling efficient state sharing in React apps.


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 *