Skip to content

Instantly share code, notes, and snippets.

@wklsh
Last active February 13, 2022 14:34
Show Gist options
  • Save wklsh/8a483c86ff8e91cd50dc616ac12de054 to your computer and use it in GitHub Desktop.
Save wklsh/8a483c86ff8e91cd50dc616ac12de054 to your computer and use it in GitHub Desktop.
Redux-like React Context Example

Redux-like React Context example

Example Setup of a redux-like react context. For reference visit this guide, or this guide.

Store

import React, { createContext, useReducer } from "react";

export const UIContext = createContext();

const initialStore = {
  navTheme: "black",
};

function UIProvider({ children }) {
/* --------------------------------- Reducer -------------------------------- */
  const reducer = (state, action) => {
    switch (action.type) {
      case "UPDATE_NAV_THEME":
        return {
          ...state,
          navTheme: action.theme,
        };

       default:
        throw new Error(`Unhandled action type: ${action.type}`);
      }
   };
	
  /* --------------------------------- Actions -------------------------------- */
  const updateNavTheme = (themeColor) => {
    dispatch({ type: "UPDATE_NAV_THEME", theme: themeColor });
  };

  /* -------------------------------- ends here ------------------------------- */
  const [state, dispatch] = useReducer(reducer, initialStore);
  return <UIContext.Provider value={{ ...state, updateNavTheme }}>{children}</UIContext.Provider>;
}

export default UIProvider;

app.js

import UIProvider from "../store";

function App() {
  return (
    <UIProvider>
      {/* ...component */}
    </UIProvider>
  );
}

export default App;

Usage in module

import React, { useContext } from "react";

import { UIContext } from "../../../Context/UIContext";

function Module() {
  const {
    state: { navTheme = "black" },
  } = useContext(UIContext);

  return <></>
}

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