How to Use Context API basically (with Authentication Example) ?

Hello! This is my study notes while watching Maximilian Schwarzmuller. There is no intention of being an elaborate article.

Firstly, create a context file (js). (It should be in a file whose name is not important but ‘context’ will be better) This context behaves like global variable (Difference: we decide where it is available)

Create Context supplies us to initialize our context with a default value.

//auth-context.jsimport React from 'react;const auth-context = React.createContext({    authenticated: false,
login: () => {}
});export default authContext;

Wherever we should use this context, firstly import it.

import AuthContext from '../context/auth-context.js'

Now, we can use it as component. It should wrap the components which context will be used. It is used with Provider. This Provider takes a value. So we manipulate the default value in context. Generally, default value is not used because it is managed according to states.

We bind it to state. So, changing of authenticated value of context does not render the page. But, whenever authenticated state is changed, it will be rendered.

<AuthContext.Provider 
value={{
authenticated: this.state.authenticated,
login: this.loginHandler
}}
>
<Profile/></AuthContext.Provider>

Now, we should use it in other components. In above example, it is Profile component.

//Profile.jsimport AuthContext from '../context/auth-context.js'
.
.
.
render(){ return <AuthContext.Consumer> { context => context.authenticated ? <...../> : <...../> } </AuthContext.Consumer>}}

In here, context will be consumed. The place where it returns JSX code (where context values willl be used), context should wrap the rest of code. It takes a function, and this function uses the context (in here, context keywork can be changed)

This is the way when we use it in render method. What if we need to use Context outside of render? The answer is using contextType.

class Profile extends Component {    static contextType = AuthContext}

Now, we can use Context in lifecycle methods with ‘context’ keyword.

class Profile extends Component {    static contextType = AuthContext    componentDidMount(){    const user = this.context     }}

What about functional components? How do we use it? The answer in here is ‘useContext’

import React, { useContext } from 'react' 
import AuthContext from './auth-context'
function Profile() { const authContext = useContext(AuthContext) console.log(authContext)
// { authenticated: false,
// login: () => {} }
return null
}

‘useContext’ has the same behaviour with

‘static contextType = AuthContext’

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store