Context Api in React JS and UseContext Hook to resolve the mess
import "./styles.css";
import A from "./A";
import { createContext } from "react";
//context Api
const Fname = createContext();
export default function App() {
return (
<div className="App">
<Fname.Provider value={"biplav"}>
<A />
</Fname.Provider>
</div>
);
}
export {Fname};
import React from "react";
import B from "./B";
function A() {
return (
<div>
<B />
</div>
);
}
export default A;
import React from "react";
import C from "./C";
function B() {
return (
<div>
<C />
</div>
);
}
export default B;
import React from "react";
import {Fname} from "./App"
function C(){
return (
<div>
<Fname.Consumer>{
function name(cname){
return (
<div>
<h1>Hello This is context Api in React Js </h1>
<h1>Hii {cname} </h1>
</div>
)
}
}
</Fname.Consumer>
</div>
)
}
export default C;
if we want to use context API with more than one
import "./styles.css";
import A from "./A";
import { createContext } from "react";
//context Api
const Fname = createContext();
const Lname = createContext();
export default function App() {
return (
<div className="App">
<Fname.Provider value={"biplav"}>
<Lname.Provider value={"Mazumdar"}>
<A />
</Lname.Provider>
</Fname.Provider>
</div>
);
}
export { Fname, Lname };
in between A,B is there
import React from "react";
import {Fname,Lname} from "./App"
function C(){
return (
<div>
<Fname.Consumer>{
function name(cname){
return (
<Lname.Consumer>
{function Last(L_name){
return (
<>
<h1>Hello This is context Api in React Js </h1>
<h1>Hii {cname} {L_name} </h1>
</>
)
}
}
</Lname.Consumer>
)
}
}
</Fname.Consumer>
</div>
)
}
export default C;
if we don't want this type of mess we are using the useContext Hook
import "./styles.css";
import A from "./A";
import { createContext } from "react";
//context Api
const Fname = createContext();
const Lname = createContext();
export default function App() {
return (
<div className="App">
<Fname.Provider value={"biplav"}>
<Lname.Provider value={"Mazumdar"}>
<A />
</Lname.Provider>
</Fname.Provider>
</div>
);
}
export { Fname, Lname };
import React, { useContext } from "react";
import { Fname, Lname } from "./App";
function C() {
const context = useContext(Fname);
const text = useContext(Lname);
return (
<div>
<h1>
My name is {context} {text}
</h1>
</div>
);
}
export default C;
Comments
Post a Comment