I would like to have a global variable that I can edit anywhere using hooks.
In the example I have 2 components both using the same hook. It seems to me that the External toggle
is editing its own scoped count
and Internal Toggle
is changing its own scope also.
Is it possible have both toggles edit the same data?
Code example: https://codesandbox.io/s/520zvyjwlp
index.js
function ChangeCount() {
const { count, increment } = useCounter();
return <button onClick={() => increment(!count)}>External Toggle</button>;
}
function App() {
const { count, increment } = useCounter();
return (
<div>
{`${count}`}
<br />
<ChangeCount />
<br />
<button onClick={() => increment(!count)}>Internal Toggle</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
useCount.js
import { useState } from "react";
export default function useCounter() {
const [count, setCount] = useState(false);
const increment = (changeCount) => setCount(changeCount);
return { count, increment };
}