How to: persist a valtio state

Why valtio?

Local persistence

import { proxy } from 'valtio';

const state = proxy({ todos: [] });
subscribe(state, () => {
localStorage.set('todosState', JSON.stringify(state));
});
const storedStateString = localStorage.getItem('todosState');
const initialState = storedStateString ? JSON.parse(storedStateString) : { todos: [] };
// states/todos.js
import { proxy } from 'valtio';
const storedStateString = localStorage.getItem('todosState');
const initialState = storedStateString ? JSON.parse(storedStateString) : { todos: [] };
const state = proxy(initialState);subscribe(state, () => {
localStorage.set('todosState', JSON.stringify(state));
});
export default state;

React Native & AsyncStorage

// states/todos.js
import AsyncStorage from '@react-native-async-storage/async-storage';
import { proxy } from 'valtio';

const state = proxy({ todos: [], hydrated: false });
subscribe(state, () => {
AsyncStorage.setItem('todosState', JSON.stringify(state));
});
export const hydrateState = async () => {
const storedStateString = await AsyncStorage.getItem('todosState');
if(storedStateString){
state.todos = JSON.parse(storedStateString).todos;
}
state.hydrated = true;
}
export default state;// App.tsx
import { useSnapshot } from 'valtio';
import React, { useEffect } from 'react';
import state, { hydrateState } from './states/todos';
const App = () => {
const { hydrated, todos } = useSnapshot(state);
useEffect(() => {
hydrateState();
}, []);
if(hydrated){
// Return your actual component which renders the app
}
// return a loading screen
}

Closing thoughts

You may check my website for my bio, at http://t.co/BlvwH2JyeT.