Skip to content

Instantly share code, notes, and snippets.

@devwax
Last active April 3, 2022 19:36
Show Gist options
  • Save devwax/e1f3b62ebca7e4a6363307862a1fc974 to your computer and use it in GitHub Desktop.
Save devwax/e1f3b62ebca7e4a6363307862a1fc974 to your computer and use it in GitHub Desktop.
React Context-Driven AppState Scaffolding Snippets

React Context-Driven AppState Scaffolding

  • /context/

    • AppState.js
    • app-context.js
  • Wrap App _(app.js)

    import AppState from "../context/AppState";
    <AppState>
      ...
    <AppState>
  • User in components with context hook

    import React, { useState, useEffect, useContext } from 'react'
    import AppContext from "../../context/app-context";
    const { randomAgent, setRandomAgent } = useContext(AppContext);

AppState.js

import React, { useState } from "react";
import AppContext from "./app-context";

const AppState = (props) => {
//   const [isAuth, setIsAuth] = useState(true);
  const [randomAgent, setRandomAgent] = useState(null)

  return (
    <AppContext.Provider
      value={{
        setRandomAgent,
        randomAgent
      }}
    >
      {props.children}
    </AppContext.Provider>
  );
};

export default AppState;

app-context.js

import { createContext } from "react";

const appContext = createContext();

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