Skip to content

Instantly share code, notes, and snippets.

@nurmuhammadsirat
Last active May 23, 2023 08:58
Show Gist options
  • Save nurmuhammadsirat/a696966213719ba5728992cfb9d92066 to your computer and use it in GitHub Desktop.
Save nurmuhammadsirat/a696966213719ba5728992cfb9d92066 to your computer and use it in GitHub Desktop.
React context pattern (typescript)
import { MyContextProvider } from './MyContextProvider;
import { SubComponent } from './SubComponent;
const Component = () => {
return (
<MyContextProvider>
<SubComponent> ... </SubComponent>
</MyContextProvider>
);
}
type MyContextType = {
strValue: string;
numValue: number;
}
const MyContext = createContext<MyContextType>({} as MyContextType);
type Props = {
children: ReactNode;
}
export const MyContextProvider = ({children}: Props) => {
const [someVal, setSomeVal] = useState('')
useEffect(() => {
// do stuff
}, []);
return (
<MyContext.Provider value={ {strValue: 'some string', numValue: 123 } }>
{children}
</MyContext.Provider>
)
}
export const useMyContext = () => {
const context = useContext(MyContext);
if (!context) {
throw new Error(`useMyContext must be used within a MyContext.Provider`);
}
return context;
};
import { useMyContext } from './MyContextProvider;
const SubComponent = () => {
const { strValue, numValue } = useMyContext();
return (
<div>
<div>strValue</div>
<div>numValue</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment