Skip to content

Instantly share code, notes, and snippets.

@tnhu
Created November 24, 2021 23:30
Show Gist options
  • Save tnhu/07e0145b42834b5205dbd1e303139505 to your computer and use it in GitHub Desktop.
Save tnhu/07e0145b42834b5205dbd1e303139505 to your computer and use it in GitHub Desktop.
Six simple steps to create and use React Context #react #typescript #context
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