Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React hook: useAuth
import React, { useCallback, useState, useEffect, useContext, createContext } from 'react'
const authContext = createContext()
// Hook for child components to get the auth object and re-render when it changes.
export default () => {
return useContext(authContext)
}
// Provider component that wraps components and makes useAuth() available
export function ProvideAuth({ children }) {
const auth = useAuthProvider()
return <authContext.Provider value={auth}>{children}</authContext.Provider>
}
// Provide Auth hook that creates auth object and handles state
function useAuthProvider() {
const [user, setUser] = useState(null)
// Get the logged in user when created
useEffect(() => {
const user = getLoggedInUser()
setUser(user)
}, [])
const login = async (...) => {
const user = ...
setUser(user)
}
const logout = async () => {
...
setUser(null)
}
const resetPassword = async () => {
...
}
return {
resetPassword
login,
logout,
user
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment