Skip to content

Instantly share code, notes, and snippets.

@DanielHoffmann
Last active July 13, 2020 08:50
Show Gist options
  • Save DanielHoffmann/3da260281fa8de994512433f905c331f to your computer and use it in GitHub Desktop.
Save DanielHoffmann/3da260281fa8de994512433f905c331f to your computer and use it in GitHub Desktop.
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