usestate-js is a 276 byte zero-dependency module that recreates
React useState
in vanilla JavaScript.
You can read about how I wrote it or try it now on CodePen.
<script src="https://unpkg.com/usestate-js"></script>
<body><script>
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
document.body.innerHTML = `
<div>
<p>You clicked ${count} times</p>
<button>
Click me
</button>
</div>
`;
document.body.querySelector('button').onclick = () => setCount(count + 1);
}
connect(Example)();
</script></body>
<script src="https://unpkg.com/usestate-js"></script>
<script>
class CounterExample extends HTMLElement {
constructor () {
super();
this.attachShadow({ mode: 'open' });
// connect and run render()
this.render = connect(this.render);
this.render();
}
render () {
const [count, setCount] = useState(0);
// update the component innerhtml
this.shadowRoot.innerHTML = `
<p>You clicked ${count} times</p>
<button>Click me</button>
`;
// bind the setter to the button
this.shadowRoot.lastElementChild.onclick = () => setCount(count + 1);
}
}
customElements.define('counter-example', CounterExample);
</script>
<body>
<counter-example></counter-example>
<counter-example></counter-example>
</body>
Add usestate-js to your project:
npm install usestate-js
Import usestate-js to connect
functions with useState
:
import { connect, useState } from 'usestate-js';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
document.body.innerHTML = `
<div>
<p>You clicked ${count} times</p>
<button>
Click me
</button>
</div>
`;
document.body.querySelector('button').onclick = () => setCount(count + 1);
}
connect(Example)();