Skip to content

Instantly share code, notes, and snippets.

@cyberinferno
Created September 26, 2020 15:35
Show Gist options
  • Save cyberinferno/9592bb76e23677f1de5a20f81ae265c4 to your computer and use it in GitHub Desktop.
Save cyberinferno/9592bb76e23677f1de5a20f81ae265c4 to your computer and use it in GitHub Desktop.

Revisions

  1. cyberinferno created this gist Sep 26, 2020.
    44 changes: 44 additions & 0 deletions CustomContext.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    /**
    * Usage:
    *
    * export default function MyComponent() {
    * const customVariable = useCustom();
    * const changeCustomVarible = useCustomUpdate();
    * // Call change custom variable function to change value to reflect to all other places
    * }
    * <CustomProvider><MyComponent /></CustomProvider>
    */
    import React, { useContext, useState } from 'react';

    const CustomContext = React.createContext();
    const CustomContextUpdate = React.createContext();

    /**
    * Get current custom variable hook
    */
    export function useCustom() {
    return useContext(CustomContext);
    }

    /**
    * Update custom variable hook
    */
    export function useCustomUpdate() {
    return useContext(CustomContextUpdate);
    }

    export default function CustomProvider({ children }) {
    const [customVariable, setCustomVariable] = useState('');

    function changeCustomVariable(value) {
    setCustomVariable(value);
    }

    return (
    <CustomContext.Provider value={customVariable}>
    <CustomContextUpdate.Provider value={changeCustomVariable}>
    {children}
    </CustomContextUpdate.Provider>
    </CustomContext.Provider>
    );
    }