Created
May 6, 2023 19:15
-
-
Save johan44co/707a39470f9f34e5d000597592ee0d2e to your computer and use it in GitHub Desktop.
Using React Context API with TypeScript can make managing state across components a breeze! Check out this code snippet to see how it's done π #React #TypeScript #WebDevelopment
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 } from 'react'; | |
// define the shape of your context value | |
interface AppContextValue { | |
count: number; | |
incrementCount: () => void; | |
} | |
// create the context with initial values | |
const AppContext = createContext<AppContextValue>({ | |
count: 0, | |
incrementCount: () => {}, | |
}); | |
// define a component that provides the context value | |
const AppProvider: React.FC = ({ children }) => { | |
const [count, setCount] = useState(0); | |
const incrementCount = () => { | |
setCount((prevCount) => prevCount + 1); | |
}; | |
const value: AppContextValue = { | |
count, | |
incrementCount, | |
}; | |
return <AppContext.Provider value={value}>{children}</AppContext.Provider>; | |
}; | |
// define a custom hook to consume the context value | |
const useAppContext = () => useContext(AppContext); | |
// use the context value in a component | |
const ExampleComponent: React.FC = () => { | |
const { count, incrementCount } = useAppContext(); | |
return ( | |
<div> | |
<p>Count: {count}</p> | |
<button onClick={incrementCount}>Increment</button> | |
</div> | |
); | |
}; | |
// use the AppProvider to wrap your app and provide the context value | |
const App: React.FC = () => { | |
return ( | |
<AppProvider> | |
<ExampleComponent /> | |
</AppProvider> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment