-
-
Save drewjoh/d02e53c784af91955d58c49f83a8fedf to your computer and use it in GitHub Desktop.
Context Example
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 } from 'react' | |
export default createContext(null) |
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 React, { useState } from 'react' | |
import AccountContext from '../contexts/AccountContext' | |
function AccountProvider({ children }) { | |
const [account, setAccount] = useState(null) | |
return ( | |
<AccountContext.Provider value={[ account, setAccount ]}> | |
{children} | |
</AccountContext.Provider> | |
) | |
} | |
AccountProvider.propTypes = { | |
children: PropTypes.node.isRequired | |
} | |
export default AccountProvider |
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 React from 'react' | |
import ReactDOM from 'react-dom' | |
import App from './components/app/App' | |
import AccountProvider from './providers/AccountProvider' | |
ReactDOM.render( | |
<AccountProvider> | |
<App /> | |
</AccountProvider>, | |
document.getElementById('root') | |
) |
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 React from 'react' | |
import useAccount from '../hooks/useAccount' | |
function MyComponent() { | |
const [account, setAccount] = useAccount() | |
return <div>{account ? account.firstName : 'No Account'}</div> | |
} | |
export default MyComponent |
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 { useContext } from 'react' | |
import AccountContext from '../contexts/AccountContext' | |
function useAccount() { | |
const value = useContext(AccountContext) | |
if (value === null) | |
throw new Error('<AccountProvider> is not in the parent tree') | |
return value | |
} | |
export default useAccount |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment