Introduction to Context API in React JS | Lecture 23 | Creating React JS from the ground up

Posted by

Context API in React JS | Lecture 23 | React JS from scratch

Welcome to Lecture 23: Context API in React JS

In this lecture, we will be discussing the Context API in React JS. Context provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered “global” for a tree of React components, such as the currently authenticated user, theme, or preferred language.

The Context API consists of two main parts: the Provider and the Consumer. The Provider is used to wrap the components that need access to the shared data, and the Consumer is used within the components to access that shared data.

Example of using Context API

const MyContext = React.createContext();

class MyProvider extends React.Component {
  state = {
    data: 'This is some shared data'
  }

  render() {
    return (
      
        {this.props.children}
      
    )
  }
}

class MyComponent extends React.Component {
  static contextType = MyContext;

  render() {
    return (
      

MyComponent

{this.context}

) } } class App extends React.Component { render() { return ( ) } } ReactDOM.render(, document.getElementById('root'));

In this example, we create a context using React.createContext() and then define a Provider and a Consumer. The Provider wraps the components that need access to the shared data, and the Consumer is used within those components to access the shared data.

Conclusion

The Context API in React JS provides a convenient way to share data across the component tree without having to pass props manually at each level. It is particularly useful for sharing global data such as authentication state, theme, or language preferences.

That’s all for this lecture. Stay tuned for more React JS tutorials!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sauravsharma3819
6 months ago

thankyouu so muc didi
ive tried from so many videsos to understand this topic but couldn't but you just made it so easy to understand in few minutes only thankyou so muc