Skip to content

Instantly share code, notes, and snippets.

@james-gardner
Last active August 10, 2020 08:10
Show Gist options
  • Save james-gardner/7a9770df2ff9388553d3b4e54a9e7f7f to your computer and use it in GitHub Desktop.
Save james-gardner/7a9770df2ff9388553d3b4e54a9e7f7f to your computer and use it in GitHub Desktop.
useReducer + context
import React, { useReducer, useContext, createContext } from 'react'
import PropTypes from 'prop-types'
const SomethingUsefulContext = createContext()
export const reducer = ( state, action ) => {
switch(action.type) {
default:
throw new Error(`Unrecognised action type: ${action.type} `)
}
}
export const SomethingUsefulProvider = ({ children }) => (
<SomethingUsefulContext.Provider value={useReducer(reducer, initialState)}>
{children}
</SomethingUsefulContext.Provider>
)
SomethingUseful.propTypes = {
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired
}
export const useSomethingUseful = () => useContext(SomethingUsefulContext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment