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.
Custom context react
/**
* 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>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment