Change detection using proxy and immutable state generation, re-rendering optimization
π 1. What is Valtio?
Key Features
A method that uses Proxy to track state and automatically updates only related components when state changes
In other words, you can modify state objects as comfortably as handling them directly, and Valtio detects those changes and re-renders only necessary parts
It wraps state objects with Proxy to detect all access to state. It identifies which parts of state each component reads and re-renders only that component when those parts change
You can read current state snapshots with the useSnapshot hook, and automatically receive updated snapshots when state changes
Since you can change state as you handle existing JS objects, the learning curve is low
Being Proxy-based, caution may be needed in unpredictable scenarios
Example Code
import{proxy,useSnapshot}from'valtio';// 1. State definition: Use proxy function to wrap state with Proxyconststate=proxy({count:0,text:'Hello',});// 2. Component that reads and changes statefunctionCounter(){ // Get current state snapshot with useSnapshotconstsnap=useSnapshot(state);return (<div><p>Count: {snap.count}</p><buttononClick={() =>state.count++}>+1</button></div> );}functionTextDisplay(){constsnap=useSnapshot(state);return (<div><p>Text: {snap.text}</p><buttononClick={() => (state.text=state.text+'!')}>Add "!"</button></div> );}exportdefaultfunctionApp(){return (<div><h1>Valtio Example</h1><Counter/><TextDisplay/></div> );}
π 2. When is it Good to Use Valtio?
When is it Good to Use Valtio?
When you want to easily define and update global state
When you want to change state intuitively like state.count++
When is it Better Not to Use Valtio?
When strict patterns are needed in large-scale projects (in such cases, it would be better to use consistent patterns like Redux's action, reducer)
When complex debugging or tracking features are needed like Redux's MobX, Valtio's Proxy-based rendering optimization can become a disadvantage
When type safety is needed, Valtio's loose structure can become a disadvantage
My Thoughts
This chapter introduces Valtio, which takes a different approach to state management by using Proxy for automatic change detection. The key insight is that Valtio provides a more intuitive way to work with state by allowing direct mutations while still maintaining React's optimization benefits.
The discussion about when to use Valtio vs. when not to use it is particularly valuable - it shows that while Valtio is powerful and easy to use, it's not always the best choice for every project.
The Proxy-based approach is interesting because it provides automatic optimization without requiring developers to manually specify dependencies or use selectors.