Last active
August 10, 2020 08:10
-
-
Save james-gardner/7a9770df2ff9388553d3b4e54a9e7f7f to your computer and use it in GitHub Desktop.
useReducer + context
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, { 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