Just randomly reading into React over this example, I'm surprised by how React itself confused me with the useState function.
let _count = 0;
function Component() {
return (
<div>
<div>{_count}</div>
<button onClick={() => { _count++; render(); }}>Increase</button>
</div>
);
}
function render() {
React.render(<Component />, root)
}
Or you can abstract it: let _count;
function useCount(initialValue) {
return [_count, (value) => { _count = value; render(); }]
}
function Component() {
const [count, setCount] = useCount(0);
return (
<div>
<div>{count}</div>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
And then generalize it and make each state dependent on the order of useState calls: const states = [];
function useState(initialValue) {
const state = states.shift() || { value: initialValue }; // Pop or create
setTimeout(() => states.push(state), 0); // Defer the push
return [state.value, (value) => { state.value = value; render(); }];
}
function Component() {
const [count, setCount] = useState(0);
const [name, setName] = useState('World');
return (
<div>
<div>{count}</div>
<button onClick={() => setCount(count + 1)}>Increase</button>
<h1>Hello {name}</h1>
<input value={name} onChange={(e) => setName(e.currentTarget.value)} />
</div>
);
}
Actual hooks also track the component that's being rendered, and don't just call the global render function, but that's pretty much the whole useState implementation.Here's a codepen: https://codepen.io/lxe/pen/RwbXPKo
... or you can use something like Statium's ViewModel, which is basically a hierarchically linked, locally scoped state container component: https://github.com/riptano/statium
RealWorld example: https://github.com/nohuhu/react-statium-realworld-example-ap...
Sorry... Just... Couldn't... :)