How to use Context API for authentication (firebase) in ReactJS

How to use Context API for authentication (firebase) in ReactJS

Context API and Firebase

ยท

4 min read

In this article, we are going to cover:

  • What is the context?
  • Why use context?
  • How to use context API?

Prerequisites:

  • Basic knowledge of React.
  • Basic working of firebase.

ltts get started.gif

1. What is the context? ๐Ÿค”

According to React doc:

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

2. Why use context? ๐Ÿง

As we have seen in the definition of context, it is used to pass data from parent to child. So, suppose you want to pass the data from component A to component D in component tree A->B->C->D you need to pass the props from A to B and then B to C, and then finally from C to D.

Even though components B and C have nothing to do with this data we have to pass the props wherever we use those components. As you see it's a cumbersome process.

But thanks to Context we can save ourselves from this cumbersome process๐Ÿ˜Œ

In context, we store the data which we wanna pass down the props in global space or you can say in the data layer and with the help of ContextAPI, we can directly use this data in whichever component we want.

3. How to use context API?๐Ÿ˜ƒ

First, create the js file to create the context. In this tutorial, we are using it for authentication so I create the file name auth-context.js you can choose whichever name you like.

Now import the files which you need

import React, {useState} from 'react';
import { auth, provider } from '../firebase';

auth and provider are the constant which we export from the firebase.js file

import firebase from 'firebase/app';
import 'firebase/auth';

const auth = firebase.auth();
const provider =  new firebase.auth.GoogleAuthProvider();

As we are using google authentication we need a provider.

Now, to create the context, we use React.createContext() and pass some initial values( optional but it will give you nice auto-completion while using context ) of the data we want to start.

export const AuthContext = React.createContext({
    user: null,
    login: () => {},
    logout: () => {}
});

Then we create AuthContextProvider(the name is up to you) HOC(Higher Order Component) by using AuthContext.provider to wrap it around our App Component in the index.js file so that we can use context anywhere in our app.

const AuthContextProvider = props => {
    const [user, setUser] = useState(null);

    const loginHandler = () => {
        auth.signInWithPopup(provider)
            .then(result => setUser(result.user))
            .catch(error => console.log(error))
    }

    const logoutHandler = () => {
        auth.signOut();
        setUser(null);
    }


    return (
        <AuthContext.Provider value={{user: user, login: loginHandler,logout: logoutHandler}}>
            {props.children}
        </AuthContext.Provider>
    );
}

export default AuthContextProvider;

auth.signInWithPopup(provider) and auth.signOut() methods are provided by firebase to authenticate and log out the user.

As you see the AuthContext.provider takes the value property to initialize the data we want to store in context.

Now we can wrap AuthContextProvider around our App Component.

import AuthContextProvider from './context/auth-context';

ReactDOM.render(
  <React.StrictMode>

    <AuthContextProvider>
        <App />
    </AuthContextProvider>

  </React.StrictMode>,
  document.getElementById('root')
);

The final code in auth-context.js looks like this.

carbon.png

Now our Context is ready. To use this context in any component you just need to import AuthContext from auth-context.js file and in the functional component we use this context by using the useContext() hook.

For example:

import React, { useContext } from 'react';
import { AuthContext } from './context/auth-context'; 
function App() {
  const authContext = useContext(AuthContext);
  return();
}

We can use authContext.user for user , authContext.login() for login method and authContext.logout() for logout method.

To use context in a class component

We use static contextType

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

To consume it:

<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>

That's it for this article!

thnq.gif

ย