Skip to content

Instantly share code, notes, and snippets.

@kylelambert101
Created February 14, 2022 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelambert101/0d1a89ca391b1c9ee83d62f6f2810ab7 to your computer and use it in GitHub Desktop.
Save kylelambert101/0d1a89ca391b1c9ee83d62f6f2810ab7 to your computer and use it in GitHub Desktop.
React -> Simple Context
import * as React from 'react';
export interface SimpleContextType {
userName: string | undefined;
setUserName: (userName: string | undefined) => void;
}
export const SimpleContext = React.createContext<SimpleContextType>({ userName: undefined, setUserName: () => undefined });
export const SimpleContextProvider = ({ children }: { children: React.ReactNode }): React.ReactElement => {
const [userName, setUserName] = React.useState<string | undefined>();
const state = React.useMemo(() => ({ userName, setUserName }), [userName]);
return <SimpleContext.Provider value={state}>{children}</SimpleContext.Provider>;
};
export const useSimpleContext = (): SimpleContextType => React.useContext(SimpleContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment