Skip to content

Instantly share code, notes, and snippets.

@ELI7VH
Last active May 9, 2024 18:00
Show Gist options
  • Save ELI7VH/8ca0e90e52e902e91c3776ad7b63ad8e to your computer and use it in GitHub Desktop.
Save ELI7VH/8ca0e90e52e902e91c3776ad7b63ad8e to your computer and use it in GitHub Desktop.
React Context Boiler Plate - Typescript
import React, { createContext, useContext, useState, useEffect } from "react"
type Props = {
children: React.ReactNode
}
type Context = {
count: number
increment: () => void
}
// Just find-replace "XContext" with whatever context name you like. (ie. DankContext)
const XContext = createContext<Context | null>(null)
export const XContextProvider = ({ children }: Props) => {
const [count, setCount] = useState(0)
useEffect(() => {
setCount(42)
}, [])
const increment = () => {
setCount(count + 1)
}
return (
<XContext.Provider value={{ count, increment }}>
{children}
</XContext.Provider>
)
}
export const useXContext = () => {
const context = useContext(XContext)
if (!context)
throw new Error("XContext must be called from within the XContextProvider")
return context
}
@maksnester
Copy link

Exactly what I was looking for, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment