
import { proxy } from 'valtio'
const state1 = proxy({ count: 0, text: 'hello' })
const state2 = proxy(new User('Timo', 'Kivinen'))
const state = proxy({ a: { aa: 1 }, b: { bb: 2 } })
const snap1 = snapshot(state)
const newSnap = snapshot(state.a);
console.log(snap1) // ---> { a: { aa: 1 }, b: { bb: 2 } }
++state.a.aa
const snap2 = snapshot(state)
console.log(snap2) // ---> { a: { aa: 2 }, b: { bb: 2 } }
snap1.b === snap2.b // this is `true`, it doesn't create a new snapshot because no properties are changed.
proxy로 생성된 상태를 인자로 받아, 불변성을 지키면서 변화 부분만 최적화 하여 생성
렌더링 최적화 (아래 조건이 만족 시 렌더링)
아래 예시에서 버튼 클릭 시 state의 count가 수정되고, snap의 count가 읽히고 있기 때문에 렌더링됨.
function Counter() {
const snap = useCard();
return (
<div>
{snap.count}
<button
onClick={() => {
// also read from the state proxy in callbacks
if (state.count < 10) {
++state.count
}
}
>
+1
</button>
</div>
)
}
function Counter() {
const store = useProxy(state);
return (
<div>
{store.count}
<button
onClick={() => {
// also read from the state proxy in callbacks
if (store.count < 10) {
++store.count
}
}
>
+1
</button>
</div>
)
}