The Context API is to manage used global state in a ReactJS application. This article assumes you already know how to use the Context API and you want to find and easier way to use it in your application.
Let's get right Into it
The normal way it's done:
import React from 'react'
import AuthContext from '../provider'
export function someFunction(){
const context = React.useContext(AuthStateContext);
}
This is generally how we import state from the context provider into the component we want to use it in. However, there is always a way to simplify this process by creating a custom hook that implements the React.useContext()
hook without having to call it in every class or function you create.
Let's Create our UseAuthState Hook
const AuthStateContext = React.createContext();
export function useAuthState() {
const context = React.useContext(AuthStateContext);
if (context === undefined) {
throw new Error('useAuthState must be used within a AuthProvider');
}
return context;
}
We need this hook to throw an error because we don't want it to be used outside the provider which holds the state.
How to implement
import React from 'react'
import {useAuthState} from 'src/provider'
export function UserDetails(){
const {user} = useAuthState()
}
This makes useContext easier and faster to use across all components in the application.