Skip to content

Instantly share code, notes, and snippets.

@chriskavanagh
Last active February 20, 2024 02:11
Show Gist options
  • Save chriskavanagh/411bd7a807b4615b7d493590d5e56d92 to your computer and use it in GitHub Desktop.
Save chriskavanagh/411bd7a807b4615b7d493590d5e56d92 to your computer and use it in GitHub Desktop.
react context
import { useState, createContext, useContext } from "react";
const CounterContext = createContext(null);
const CounterContextProvider = ({ children }) => (
<CounterContext.Provider value={useState(0)}>
{children}
</CounterContext.Provider>
);
const Container = () => (
<div>
<AddOneButton />
</div>
);
const AddOneButton = () => {
const [, setCounter] = useContext(CounterContext);
return (
<div>
<button onClick={() => setCounter((v) => v + 1)}>Add One</button>
</div>
);
};
const Counter = () => {
const [counter] = useContext(CounterContext);
return <div>Counter: {counter}</div>;
};
export default function CounterUseContext() {
//const [counter, setCounter] = useState(0);
return (
<CounterContextProvider>
<div>
<Container />
<Counter />
</div>
</CounterContextProvider>
);
}
//App
import "./styles.css";
import { useState } from "react";
import CounterUseContext from "./counter-context";
export default function App() {
return (
<div className="App">
<CounterUseContext />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment