The useContext hook in React allows components to consume values from the React context. React’s context API is primarily designed to pass data down the component tree without manually passing props at every level. useContext is a part of React's hooks system that enables functional components to access context values.
- Simplifies accessing shared state across components.
- Avoids prop drilling by eliminating the need to pass props down multiple levels.
- Works seamlessly with React's Context API to provide global state
Syntax
const contextValue = useContext(MyContext);
- MyContext: The context object is created using React.createContext().
-
contextValue: The current context value that we can use in our component.
**Implementing the useContext Hook**
Implementing the useContext Hook involves creating a context, providing its value through a provider component, and consuming that shared value directly within functional components.
1.Passing Data Between Sibling Components Using Context
Sometimes, two sibling components need to share data. useContext helps avoid lifting state unnecessarily.
App.jsx
import React, { useContext, useState } from "react";
import MessageContext from "./MessageContext";
import "./App.css";
function Parent() {
const [message, setMessage] = useState("Hello from Child A");
return (
<MessageContext.Provider value={{ message, setMessage }}>
<div className="container">
<Header />
<div className="children-container">
<ChildA />
<ChildB />
</div>
</div>
</MessageContext.Provider>
);
}
function Header() {
return (
<div className="header">
<h2>GeeksforGeeks</h2>
<p>Passing Data Between Siblings using React Context API</p>
</div>
);
}
function ChildA() {
const { setMessage } = useContext(MessageContext);
return (
<div className="card">
<h3>Child A</h3>
<input
type="text"
placeholder="Update message"
onChange={(e) => setMessage(e.target.value)}
className="input"
/>
</div>
);
}
function ChildB() {
const { message } = useContext(MessageContext);
return (
<div className="card">
<h3>Child B</h3>
<p className="message">
<strong>Message from A:</strong> {message}
</p>
</div>
);
}
export default function App() {
return <Parent />;
}
MessageContext.jsx
import { createContext } from "react";
const MessageContext = createContext();
export default MessageContext;
OUTPUT:

Top comments (0)