Created
November 24, 2021 23:30
-
-
Save tnhu/07e0145b42834b5205dbd1e303139505 to your computer and use it in GitHub Desktop.
Six simple steps to create and use React Context #react #typescript #context
This file contains 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 React, { useState, useContext } from 'react' | |
// 1. Define data that the context holds, plus a setter to update data | |
interface MyContextProps { | |
standalone: boolean | |
setMyContext: (value: Partial<Omit<MyContextProps, 'setMyContext'>>) => void | |
} | |
// 2. Create the actual context with some default data | |
const MyAppContext = React.createContext<MyContextProps>({ | |
standalone: true, | |
setMyContext: () => {} | |
}) | |
// 3. Define the context provider | |
export const MyContextProvider: React.FC<{ value: MyContextProps }> = ({ value: initialValue, children }) => { | |
const [states, setStates] = useState<MyContextProps>(initialValue) | |
return ( | |
<MyAppContext.Provider | |
value={{ | |
...states, | |
setMyContext: props => { | |
setStates({ ...states, ...props }) | |
} | |
}}> | |
{children} | |
</MyAppContext.Provider> | |
) | |
} | |
// 4. Make a hook to use the context easier | |
export const useMyContext = () => useContext(MyAppContext) | |
// 5. Use the context provider in some root (i.e: App.tsx) | |
// <MyContextProvider value={{...}}/> | |
// 6. Use hook to get and set context data | |
// const { foobar, setContext } = useMyContext() | |
// ... | |
/// setContext({ foobar: !foobar }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment