Skip to content

Instantly share code, notes, and snippets.

@cassidoo
Created July 30, 2020 06:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cassidoo/4239c2fc1d9bed44941166637c3c7651 to your computer and use it in GitHub Desktop.
Save cassidoo/4239c2fc1d9bed44941166637c3c7651 to your computer and use it in GitHub Desktop.
An example of component-izing context
//////// Some App file that uses the things we made
import React from "react"
import { LoggedIn, LoggedOut } from "app/thingies"
import { AppStateProvider } from "app/app-state"
import appReducer, { initialState } from "app/appReducer"
function App() {
const { authAttempted, auth } = useAuth()
return <div className="Layout">{auth ? <LoggedIn /> : <LoggedOut />}</div>
}
export default () => (
<AppStateProvider reducer={appReducer} initialState={initialState}>
<App /> {/* So everything inside of <App /> can use the app reducer and the defined state for this context */}
</AppStateProvider>
)
//////// Our context file
import React, { createContext, useReducer, useContext } from "react"
const Context = createContext()
export function AppStateProvider({ reducer, initialState = {}, children }) {
const value = useReducer(reducer, initialState)
return <Context.Provider value={value} children={children} />
}
export function useAppState() {
return useContext(Context)
}
//////// Our reducer file
const initialState = { user: null, something: 'what' }
const appStateReducer = (state, action) => {
switch (action.type) {
case "AUTH_CHANGE": {
return { ...state, user: action.user }
}
case "DO_SOMETHING": {
return { ...state, something: 'how' }
}
default:
return state
}
}
export { initialState }
export default appStateReducer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment