Skip to content

Instantly share code, notes, and snippets.

@GabeDuarteM
Last active August 30, 2020 02:23
Show Gist options
  • Select an option

  • Save GabeDuarteM/3a48f17d997ec004dcc0dfc505d9bde2 to your computer and use it in GitHub Desktop.

Select an option

Save GabeDuarteM/3a48f17d997ec004dcc0dfc505d9bde2 to your computer and use it in GitHub Desktop.
React context utils
import React from 'react';
export function createContext<ContextValueType extends {} | null>(): readonly [
() => ContextValueType,
React.Provider<ContextValueType | undefined>,
] {
const context = React.createContext<ContextValueType | undefined>(
undefined,
);
function useContext(): ContextValueType {
const value = React.useContext(context);
if (value === undefined) {
throw new Error(
'useContext must be inside a Provider with a value',
);
}
return value;
}
return [useContext, context.Provider] as const;
}
import React from "react";
import createContext from './createContext';
const [useUserInfoContext, UserInfoProviderInternal] = createContext<
string
>();
export { useUserInfoContext };
export const UserInfoProvider: React.FC = ({ children }) => {
const value = ""
return (
<UserInfoProviderInternal
value={value}
>
{children}
</UserInfoProviderInternal>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment