Hooks: useState
Returns an array of two values. The first value is the immutable state that is initialized to the argument you pass in. The second value is the function that is used to change the first value (the setter).
When the setter is called, the element in which the state resides is rerendered.
import { component, html, useState, useEffect } from 'haunted';
customElements.define('use-state', component(function Counter() {
const [count, setCount] = useState(0);
return html`
Count: ${count}
<button @click=${() => setCount(count + 1)}>Increment</button>
`;
}));
<script type="module" src="use-state.js"></script>
<use-state></use-state>
Additionally if you provide a function as the argument to useState
, the function is called to initialize the first state, but never called again.
const [count, setCount] = useState(() => {
return expensiveComputation(42);
});
API
useState
Parameters
initialState
T
Optional initial state
Returns
readonly [state: T, updaterFn: StateUpdater<T>]
Exports
import { useState } from 'haunted/lib/use-state';