Last active
July 13, 2020 08:50
-
-
Save DanielHoffmann/3da260281fa8de994512433f905c331f to your computer and use it in GitHub Desktop.
This file contains 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
import React, { useContext, useMemo, useState } from 'react'; | |
interface ExampleContextValue { | |
value: number; | |
setValue: (newValue: number) => void; | |
} | |
const ExampleContext = React.createContext<ExampleContextValue | undefined>( | |
undefined, | |
); | |
interface ExampleContextProps { | |
children: React.ReactNode; | |
} | |
export function ExampleContextProvider({ children }: ExampleContextProps) { | |
const [value, setValue] = useState<number>(0); | |
const contextValue: ExampleContextValue = useMemo((): ExampleContextValue => { | |
return { value, setValue }; | |
}, [value]); | |
return ( | |
<ExampleContext.Provider value={contextValue}> | |
{children} | |
</ExampleContext.Provider> | |
); | |
} | |
export function ExampleContextConsumer({ | |
children, | |
}: { | |
children: (ctx: ExampleContextValue) => React.ReactNode | |
}) { | |
const ctx = useExampleContext() | |
return <>{children(ctx)}</> | |
} | |
export function useExampleContext() { | |
const context = useContext(ExampleContext); | |
if (context === undefined) { | |
throw new Error('useExampleContext must be used within a ExampleContextProvider'); | |
} | |
return context; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment