Skip to content

Instantly share code, notes, and snippets.

@adityavijay21
Last active May 2, 2024 16:57
Show Gist options
  • Save adityavijay21/7de82ab85f6e455ff49a315c77fd7391 to your computer and use it in GitHub Desktop.
Save adityavijay21/7de82ab85f6e455ff49a315c77fd7391 to your computer and use it in GitHub Desktop.
Context API
import './App.css'
import './ChildC.jsx'
import {createContext} from "react";
import ChildC from "./ChildC.jsx";
const data = createContext()
const data1 = createContext()
function App() {
const age = 23;
const name = "Aditya Vijay";
return (
<>
<data.Provider value={name}>
<data1.Provider value={age}>
<ChildC />
</data1.Provider>
</data.Provider>
</>
)
}
export default App
export {data, data1};
function ChildA (){
return(
<>
</>
}
export default ChildC;
function ChildB (){
return(
<>
</>
}
export default ChildB;
import {data,data1} from './App.jsx';
function ChildC (){
return(
<>
<data.Consumer>
{
(name) => {
return(
<data1.Consumer>
{
(age) => {
return(
<h1>I am {name} and my age is {age}.</h1>
)
}
}
</data1.Consumer>
)
}
}
</data.Consumer>
</>
)
}
export default ChildC;
- /
- src
- App.jsx
- ChildA.jsx
- ChildB.jsx
- ChildC.jsx
we use context api to avoid the prop drilling.
The Context API in React helps avoid prop drilling by passing global variables throughout the codebase.
However, it can lead to nested consumers and callback hell when dealing with numerous data providers. To address this, utilize the 'useContext' React Hook for a cleaner solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment