Skip to content

Instantly share code, notes, and snippets.

@pikonha
Created February 19, 2020 13:41
Show Gist options
  • Save pikonha/c5756546ee8c831262634e09a9b166c6 to your computer and use it in GitHub Desktop.
Save pikonha/c5756546ee8c831262634e09a9b166c6 to your computer and use it in GitHub Desktop.
A implementation of the React's ContextAPI using hooks
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 };
@pikonha
Copy link
Author

pikonha commented Feb 19, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment