For my current personal project Valtio is almost the perfect state management library for React. https://github.com/pmndrs/valtio
The benefits for me are:
- I can use the state object without worrying about unnecessary re-renders. If the value of
foochangesAppdoesn't care. - I can mutate state directly. In my real application I have deeply nested state.
import React from 'react'
import {proxy, useSnapshot} from 'valtio';
const state = proxy({ count: 0, foo: 'bar' })
export default function App() {
const snap = useSnapshot(state);
return (
<div className="App">
<h2>Number: {snap.count}</h2>
<button onClick={()=>state.count++}>+</button>
</div>
);
}
The only thing about the API I would wish to change is that you need a different object for listening to and updating state. Is there any state management library where you can use a single object for both? My perfect API would be something like:
import React from 'react'
import {proxy} from 'some-library';
const state = proxy({ count: 0, foo: 'bar' })
export default function App() {
return (
<div className="App">
<h2>Number: {state.count}</h2>
<button onClick={()=>state.count++}>+</button>
</div>
);
}
Or having to use a hook (or whatever), but the same hook for reading and writing would also be cool:
import React from 'react'
import {proxy, useSnapshot} from 'some-library';
const state = proxy({ count: 0, foo: 'bar' })
export default function App() {
const snap = useSnapshot(state);
return (
<div className="App">
<h2>Number: {snap.count}</h2>
<button onClick={()=>snap.count++}>+</button>
</div>
);
}
Is there a library with this is a similar developer experience?