Skip to content

Instantly share code, notes, and snippets.

@chrisfosterelli
Last active September 1, 2022 13:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisfosterelli/2e523b4beae43f05624920b26bb55fa0 to your computer and use it in GitHub Desktop.
Save chrisfosterelli/2e523b4beae43f05624920b26bb55fa0 to your computer and use it in GitHub Desktop.
Context Example
import { createContext } from 'react'
export default createContext(null)
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
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')
)
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
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