useValueState
The useValueState hook returns a Value from a Store and a callback to set it, following the common React useState convention.
useValueState(
valueId: string,
storeOrStoreId?: StoreOrStoreId,
): [value: ValueOrUndefined, setValue: (value: Value) => void]| Type | Description | |
|---|---|---|
valueId | string | |
storeOrStoreId? | StoreOrStoreId | The |
| returns | [value: ValueOrUndefined, setValue: (value: Value) => void] | A tuple containing the current |
This hook is useful for creating components that read and write a Value in a single line, similar to how you would use React's useState hook.
The component this is used in will re-render when the Value changes.
Example
This example creates a Store outside the application, which is used in the useValueState hook by reference.
import {createRoot} from 'react-dom/client';
import {createStore} from 'tinybase';
import React from 'react';
import {useValueState} from 'tinybase/ui-react';
const store = createStore().setValues({employees: 3});
const App = () => {
const [employees, setEmployees] = useValueState('employees', store);
return (
<span>
Employees: {employees}
<button onClick={() => setEmployees(employees + 1)}>Hire</button>
</span>
);
};
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<span>Employees: 3<button>Hire</button></span>'
const _button = app.querySelector('button');
// -> _button MouseEvent('click', {bubbles: true})
console.log(app.innerHTML);
// -> '<span>Employees: 4<button>Hire</button></span>'
root.unmount();
Since
v7.3.0