Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created July 25, 2019 06:21
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 donaldpipowitch/dda6aca890f55e84d251d188c8a8d2cb to your computer and use it in GitHub Desktop.
Save donaldpipowitch/dda6aca890f55e84d251d188c8a8d2cb to your computer and use it in GitHub Desktop.
Share useState with useContext
import React, { createContext, useState, useContext, FC } from 'react';
type ContextValue = [boolean, (value: boolean) => void] | undefined;
const FullwidthContext = createContext<ContextValue>(undefined);
const defaultState = false;
export const FullwidthProvider: FC = ({ children }) => {
const state = useState(defaultState);
return (
<FullwidthContext.Provider value={state}>
{children}
</FullwidthContext.Provider>
);
};
export function useFullwidth() {
const context = useContext(FullwidthContext);
if (!context)
throw new Error('useFullwidth must be used within a FullwidthProvider.');
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment