Last active
March 5, 2020 06:04
-
-
Save srph/6eb0298e9955a24c162a9e1707621c36 to your computer and use it in GitHub Desktop.
React: example global state with context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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