Skip to content

Instantly share code, notes, and snippets.

@cryptiklemur
Last active June 26, 2020 23:47
Show Gist options
  • Save cryptiklemur/eccfda70b786c86e67a49402895a7969 to your computer and use it in GitHub Desktop.
Save cryptiklemur/eccfda70b786c86e67a49402895a7969 to your computer and use it in GitHub Desktop.
Simple useContext example (+ useState)
import {AuthContext} from './AuthContext';
export default ({children}) => (
<AuthContext.AuthProvider initialState={userFromServer}>
{children}
</AuthContext.AuthProvider>
);
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>;
};
import {useContext} from 'react';
import {AuthContext} from './AuthContext';
export default () => {
const {user, setUser} = useContext(AuthContext);
return (
<ul>
(user && <li onClick={() => setUser(null)}>Log Out</li>}
{!user && <li><a href="/login">Log In</a></li>}
</ul>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment