Last active
May 23, 2023 08:58
-
-
Save nurmuhammadsirat/a696966213719ba5728992cfb9d92066 to your computer and use it in GitHub Desktop.
React context pattern (typescript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { MyContextProvider } from './MyContextProvider; | |
| import { SubComponent } from './SubComponent; | |
| const Component = () => { | |
| return ( | |
| <MyContextProvider> | |
| <SubComponent> ... </SubComponent> | |
| </MyContextProvider> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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