Last active
January 18, 2025 18:51
-
-
Save ELI7VH/8ca0e90e52e902e91c3776ad7b63ad8e to your computer and use it in GitHub Desktop.
React Context Boiler Plate - Typescript
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, { 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I was looking for, thanks