Context API in ReactJs

I am a fullStack developer from India
The Context API is a way to pass data through the component tree in React without having to pass props down manually at every level. It allows you to create a provider component that stores data and a consumer component that can access that data.
Here's an example of how you might use the Context API in a simple React application:
First, you need to create a context object:
const MyContext = React.createContext();
Next, you can create a provider component that wraps the component tree and stores the data that you want to make available to all of the consumer components:
class MyProvider extends React.Component {
state = {
name: 'John',
age: 30
}
render() {
return (
<MyContext.Provider value={{
state: this.state,
growOlder: () => this.setState({
age: this.state.age + 1
})
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
Finally, you can create consumer components that can access the data stored in the provider component by using the useContext hook or the Context.Consumer component:
const Person = () => {
const { state, growOlder } = useContext(MyContext)
return (
<div>
<p>Name: {state.name}</p>
<p>Age: {state.age}</p>
<button onClick={growOlder}>Grow older</button>
</div>
)
}
class Family extends React.Component {
render() {
return (
<MyContext.Consumer>
{context => (
<div>
<Person />
<Person />
</div>
)}
</MyContext.Consumer>
)
}
}
In this example, the MyProvider component stores the data for the name and age of a person, as well as a function to update the age value. The Person component uses the useContext hook to access this data and the growOlder function, and the Family component uses the Context.Consumer component to access the data for its child components.
The Context API is useful when you have data that needs to be shared by many components in your application, but you don't want to pass props down through multiple levels of the component tree. It can help you avoid prop drilling and keep your component structure clean and organized.



