React JS 19 Tutorial in Hindi #52 Context API Reactjs
What is Context API
How to work
Example
Update Data with Context API
Interview Questions
create Context : To initiate Context API.
Provider : use for update or provide data.
use Context : get data from context api.
Context API allows you to create global variables that can be consumed across the component tree, an alternative to passing props through multiple levels
import { useState } from "react";
import College from "./College";
import { SubjectContext } from "./ContextData";
export default function App() {
const [subject,setSubject]=useState('')
return (
<div style={{backgroundColor:'yellow', padding:10}}>
<SubjectContext.Provider value={subject}>
<select value={subject} onChange={(event)=>setSubject(event.target.value)}>
<option value="">Select Subject</option>
<option value="Maths">Maths</option>
<option value="History">History</option>
<option value="English">English</option>
</select>
<h1>Context API</h1>
<button onClick={()=>setSubject('')} >Clear Subject</button>
<College />
</SubjectContext.Provider>
</div>
)
}
import { createContext } from "react";
export const SubjectContext=createContext("Maths")
import ClassComponent from "./ClassComponent";
export default function College() {
return (
<div style={{backgroundColor:'orange', padding:10}}>
<h1>College Component</h1>
<ClassComponent />
</div>
)
}
import Student from "./Student";
export default function ClassComponent() {
return (
<div style={{backgroundColor:'skyblue', padding:10}}>
<h1>ClassComponent Component</h1>
<Student />
</div>
)
}
import { SubjectContext } from "./ContextData";
import Subject from "./Subject";
export default function Student() {
return (
<div style={{backgroundColor:'green', padding:10}}>
<h1>Student Component</h1>
<Subject />
</div>
)
}