Created
June 18, 2024 09:20
-
-
Save kudorgyozo/4e9f39408764ed0e3d2fbec3bb6fa53a to your computer and use it in GitHub Desktop.
react context provider compone
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"; | |
const CountContext = createContext(999999999); | |
//default value if NO provider | |
//helper hook | |
export const useCountContext = () => useContext(CountContext); | |
//helper provider | |
export const CountContextProvider = (props) => { | |
const [count, setCount] = useState(0); | |
const increment = () => { | |
setCount(c => c + 1); | |
} | |
const decrement = () => { | |
setCount(c => c - 1); | |
} | |
return (<CountContext.Provider value={{ count, setCount }}> | |
{props.children} | |
</CountContext.Provider>) | |
} |
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
root.render( | |
<React.StrictMode> | |
<CountContextProvider> | |
<App /> | |
</CountContextProvider> | |
</React.StrictMode> | |
); |
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 { useCountContext } from "./CountContext.tsx"; | |
export const SomeComponent1 = () => { | |
const { count, setCount } = useCountContext(); | |
return <div>SomeComponent1 <button onClick={() => setCount(c => c + 1)}>++ {count}</button></div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment