Skip to content

Instantly share code, notes, and snippets.

@srph
Last active March 5, 2020 06:04
Show Gist options
  • Save srph/6eb0298e9955a24c162a9e1707621c36 to your computer and use it in GitHub Desktop.
Save srph/6eb0298e9955a24c162a9e1707621c36 to your computer and use it in GitHub Desktop.
React: example global state with context
import React, { useContext } from 'react'
import { useUser } from 'contexts/User'
export default function Page() {
const user = useUser(context)
return (
<div>Your name is {user.name}</div>
)
}
import React, { useState, useContext } from 'react'
const Context = React.createContext()
export function useUser() {
return useContext(context)
}
export function UserContextProvider({ children }) {
const [user, setUser] = useState(null)
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
// fetch user data
}, [])
useEffect(() => {
if (user == null) {
return
}
// setup axios
return () => {
// remove axios interceptors
}
}, [user && user.id])
function authenticate() {
//
}
return (
<Context.Provider value={{ user, authenticate }}>
{isLoading ? null : children}
</Context.Provider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment