Skip to content

Instantly share code, notes, and snippets.

@battlesnake
Created October 28, 2023 15:28
Show Gist options
  • Save battlesnake/fef39bc737943463e912ba535adc26c6 to your computer and use it in GitHub Desktop.
Save battlesnake/fef39bc737943463e912ba535adc26c6 to your computer and use it in GitHub Desktop.
Playing with react Context hook, in playcode.io/react
import React from 'react';
const Ctx = React.createContext();
function Editor(props) {
const [value, setValue] = React.useContext(Ctx);
return (
<input type="number" value={value} onChange={React.useCallback(e => setValue(e.target.value), [])} />
);
}
function Viewer(props) {
const [value, setValue] = React.useContext(Ctx);
return (
<p>Value is <code>{value}</code></p>
);
}
export function App(props) {
const valueHook = React.useState(42);
const [value, setValue] = valueHook;
return (
<Ctx.Provider value={valueHook}>
<div style={{ background: "black", color: "white", padding: "20px" }}>
<Editor />
<Viewer />
</div>
</Ctx.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment