Created
February 19, 2020 13:41
-
-
Save pikonha/c5756546ee8c831262634e09a9b166c6 to your computer and use it in GitHub Desktop.
A implementation of the React's ContextAPI using hooks
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, { createContext, useReducer, useContext } from "react"; | |
const MyContext = createContext(); | |
const INITIAL_STATE = []; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case "PUSH": | |
return [...state, action.payload]; | |
case "REMOVE": | |
return state.filter(element => element !== action.payload); | |
default: | |
throw new Error(`Unhandled action type: ${action.type}`); | |
} | |
}; | |
const MyContextProvider = ({ children }) => { | |
const [state, dispatch] = useReducer(reducer, INITIAL_STATE); | |
return ( | |
<MyContext.Provider value={{ state, dispatch }}> | |
{children} | |
</MyContext.Provider> | |
); | |
}; | |
const useMyContext = () => { | |
const context = useContext(MyContext); | |
if (!context) | |
throw new Error("useMyContext must be used within a MyContextProvider"); | |
return context; | |
}; | |
export default { MyContextProvider, useMyContext }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a simple but powerful implementation of ContextAPI with hooks that I use for every kind of state management of a React app. It has some concepts that came from Flux architecture and can be used just like Redux without all the complexity.