Last active
June 26, 2020 23:47
-
-
Save cryptiklemur/eccfda70b786c86e67a49402895a7969 to your computer and use it in GitHub Desktop.
Simple useContext example (+ useState)
This file contains 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 {AuthContext} from './AuthContext'; | |
export default ({children}) => ( | |
<AuthContext.AuthProvider initialState={userFromServer}> | |
{children} | |
</AuthContext.AuthProvider> | |
); |
This file contains 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 {createContext, useState} from 'react'; | |
import User from '../model/User'; // Random User Model | |
interface Context { | |
user?: User; | |
setUser?: (user: User) => void; | |
} | |
const initialState: User = null; | |
export const AuthContext = createContext<Context>({}); | |
export const AuthProvider = ({children, initialState: overrideInitialState}) => { | |
const [user, setUser] = useState(overrideInitialState || initialState); | |
return <AuthContext.Provider value={{user, setUser}}>{children}</AuthContext.Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment