solid-valtio
v0.2.2
Published
๐ State management in Solid with valtio.
Downloads
19
Maintainers
Readme
solid-valtio
๐ State management in Solid with valtio.
Quick start
Install it:
npm install valtio solid-valtio
Use it:
import { proxy, useSnapshot } from 'solid-valtio'
const state = proxy({ count: 0 })
function Counter() {
const snap = useSnapshot(state)
return <button onClick={() => ++state.count}>{snap.count}</button>
}
By default, useSnapshot
returns a Solid store. If you want to use signals, you can pass an option to useSnapshot
:
function Counter() {
const snap = useSnapshot(state, { signal: true })
return <button onClick={() => ++state.count}>{snap().count}</button>
}
You can also use utils like proxyWithComputed:
import { proxyWithComputed } from 'valtio/utils'
const state = proxyWithComputed(
{
count: 1,
},
{
doubled: snap => snap.count * 2,
},
)
// Computed values accept custom setters too:
const state2 = proxyWithComputed(
{
firstName: 'Alec',
lastName: 'Baldwin',
},
{
fullName: {
get: snap => `${snap.firstName} ${snap.lastName}`,
set: (state, newValue) => {
[state.firstName, state.lastName] = newValue.split(' ')
},
},
},
)
// if you want a computed value to derive from another computed, you must declare the dependency first:
const state = proxyWithComputed(
{
count: 1,
},
{
doubled: snap => snap.count * 2,
quadrupled: snap => snap.doubled * 2,
},
)
License
MIT