Skip to content

Instantly share code, notes, and snippets.

@kudorgyozo
Created June 18, 2024 09:20
Show Gist options
  • Save kudorgyozo/4e9f39408764ed0e3d2fbec3bb6fa53a to your computer and use it in GitHub Desktop.
Save kudorgyozo/4e9f39408764ed0e3d2fbec3bb6fa53a to your computer and use it in GitHub Desktop.
react context provider compone
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>)
}
root.render(
<React.StrictMode>
<CountContextProvider>
<App />
</CountContextProvider>
</React.StrictMode>
);
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