Valtio in a Nutshell
In this lesson, we see a minimal example to familiarize ourselves with the basic usage of Valtio.
We'll cover the following...
We'll cover the following...
Import Valtio
Here’s how we import the Valtio library in our code:
import { proxy, useSnapshot } from 'valtio';
Define state
Here’s how we define the valtio state:
const personState = proxy({
firstName: 'Harry',
lastName: 'Potter',
age: 11,
});
Create view component
Here’s how we define a view component with the valtio state:
const ViewPerson = () => {
const { firstName, lastName, age } = useSnapshot(personState);
return (
<div>
<div>First Name: {firstName}</div>
<div>Last Name: {lastName}</div>
<div>Age: {age}</div>
</div>
);
};
Create edit component
Here’s how we define an edit component with the valtio state:
const EditPerson = () => {
const { firstName, lastName, age } = useSnapshot(personState);
return (
<div>
<div>First Name: <input value={firstName} onChange={e => (personState.firstName = e.target.value)} /></div>
<div>Last Name: <input value={lastName} onChange={e => (personState.lastName = e.target.value)} /></div>
<div>Age: <input value={age} onChange={e => (personState.age = e.target.value)} /></div>
</div>
);
};
Create app component
Here’s our app component:
const App = () => (
<>
<EditPerson />
<ViewPerson />
</>
);
Putting it all together
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );