Created
September 26, 2020 15:35
-
-
Save cyberinferno/9592bb76e23677f1de5a20f81ae265c4 to your computer and use it in GitHub Desktop.
Custom context react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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