Hook single shared state
by Abdul Ahmad
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
h1 {
margin-bottom: 30px;
font-weight: bold;
font-size: 28px;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
function App() {
const handleClick1 = useHandleClick();
const handleClick2 = useHandleClick2();
const store = useStore();
/* React.useEffect(() => {
setInterval(() => {
handleClick1();
}, 1000);
}, []); */
return (
<div>
<h1>
Hook single shared state
</h1>
<button onClick={handleClick1}>
button 1
</button>
<button onClick={handleClick2}>
button 2
</button>
<div>
val: { store.state.val }
</div>
<OtherComp />
</div>
);
}
function OtherComp() {
const store = useStore();
return (
<div>
other comp: { store.state.val }
</div>
);
}
function useHandleClick() {
const store = useStore();
console.log('click 1 store', store);
return () => store.update(store.state.val + 1);
}
function useHandleLog() {
const store = useStore();
return function() {
console.log('store val', store.state.val);
};
}
function useHandleClick2() {
const log = useHandleLog();
return log;
}
const STORE = {
state: {},
inited: false,
update: () => {},
};
function useStore() {
const [state, setState] = React.useState({ val: 0 });
if (!STORE.inited) {
STORE.state = state;
STORE.inited = true;
STORE.update = (val) => {
STORE.state = { val };
setState(STORE.state);
};
}
const { inited, state: storeState, update } = STORE;
return {
state: storeState,
update,
};
}
ReactDOM.render(<App />, document.querySelector("#app"));