Consumer

The consumer is how we access the data stored in Context. Any code that is contained in the Consumer tags will have access to the Context we created. Create a new component and try importing Context and creating a consumer. It’s also possible to have as many consumers as we need so we can avoid passing data through props.

import { MyContext } from "./Context"; const page = () {

return(

<MyContext.Consumer>

{({ state, authenticate }) => (

// component code goes here

// you now have access to state and values from the provider

<button onClick={authenticate} />

)}

</MyContext.Consumer>

)

}

Updating Context

If you look at the code example above, you can see how to update the context. On click of the button, we call the authenticate method that was returned by the consumer. In the provider, we created an authenticate method which updates the value isAuthenticated to true. Now the rest of your app has access to the updated value.

authenticate = () => {

this.setState({

isAuthenticated: true

});

};

Give Context to your App

To provide context to your entire app wrap your <App /> with the Context Component.

import { MyContext, MyProvider } from "./Context"; ReactDOM.render(

<MyProvider>

<MyContext.Consumer>{state => <App data={state} /></MyContext.Consumer>

</MyProvider>,

rootElement

);

You don’t have to implement the provider like this. If you only need access to the data in provider in one component, then you can just wrap that component. Since we want to have access to user information throughout our app, it makes sense to wrap our entire App with the Provider component.

Conclusion

React Context is a great introduction on how to manage state. It’s great to familiarize yourself with these basic concepts before trying a more complex solution like Redux.

I have shown an example of a global state but I would suggest creating a more specific context like a UserContext or AdminContext. Start coding and find what works for you!