Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active March 10, 2022 09:16
Show Gist options
  • Save erkobridee/a8985cdb5ba2d60590b16da7396934cf to your computer and use it in GitHub Desktop.
Save erkobridee/a8985cdb5ba2d60590b16da7396934cf to your computer and use it in GitHub Desktop.
my way of use the react context effectively
import * as React from 'react';
import MyContextProvider from 'context/MyContext';
import MyApplication from 'domain/Application';
export const App: React.FunctionComponent = () => <MyContextProvider><MyApplication/></MyContextProvider>;
export default App;
import * as React from 'react';
import { useMyContext } from 'context/MyContext';
export const Application: React.FunctionComponent = () => {
const {
attribute,
setAttribute,
optional,
setOptional
} = useMyContext();
return (
<div> {/* UI of the application */} </div>
);
};
export default Application;
/*
based on:
How to use React Context effectively
https://kentcdodds.com/blog/how-to-use-react-context-effectively
*/
import * as React from 'react';
export interface IMyContext {
attribute: string;
optional?: string;
setAttribute: (value: string) => void;
setOptional: (value?: string) => void;
}
export type TMyContext = IMyContext | null;
const MyContext = React.createContext<TMyContext>(null);
export const MyContextProvider: React.FunctionComponent = ({ children }) => {
// basic code example to illustrate
const [attribute, setAttribute] = React.useState('');
const [optional, setOptional] = React.useState<string|undefined>(undefined);
return <MyContext.Provider value={{
attribute, setAttribute,
optional, setOptional
}}>{children}</MyContext.Provider>;
}
export const useMyContext = () => {
const context = React.useContext(MyContext)
// in case where you wan't to make it mandatory
// for some other small cases which you have dynamically usage of code
// you can ignore this part and do the check if the value is present directly
// where you're using this function
if(!context) {
throw new Error('useMyContext must be used within MyProvider');
}
}
export default MyProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment