It provides a way to share data across multiple components in your application without having to pass the data down through props
- We can create a context using the
React.createContext
method and provide it with an initial value. - Next, we can use the
useContext
Hook inside any functional component that needs access to this context data.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import React, { useContext } from 'react'; import ReactDOM from 'react-dom/client'; const MyContext = React.createContext(); function MyConsumer1() { return <><MyConsumer2/></> } function MyConsumer2() { const contextValue = useContext(MyContext); return <div>{contextValue}</div>; } function MyProvider({ }) { return ( <MyContext.Provider value="My Test context string"> <MyConsumer1 /> </MyContext.Provider> ); } //App function component function App() { return ( <MyProvider/> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
OUTPUT:
My Test context string