Home

Awesome

use-valtio

CI npm size discord

Another custom hook to use Valtio proxy state

Install

npm install valtio use-valtio

Usage

import { proxy } from 'valtio/vanilla';
import { useValtio } from 'use-valtio';

const state = proxy({ count });

const Counter = () => {
  const { count } = useValtio(state);
  const inc = () => ++state.count;
  return (
    <div>
      {count} <button onClick={inc}>+1</button>
    </div>
  );
};

But, why?

Valtio has useSnapshot hook that can be used with proxy state, which is similar to useValtio.

import { useSnapshot } from 'valtio';

useSnapshot is implemented with useSyncExternalStore which is a recommended way to use "external stores". It solves tearing issues.

However, the "Sync" behavior doesn't work nicely with concurrent rendering. We can't use startTransition as expected.

useValtio doesn't use useSyncExternalStore, but only useReducer and useEffect. It suffers from tearing, but works better with concurrent rendering.

After all, it's a trade-off.

There's one caveat in useValtio. To make it work with transitions, it forces "sync=true". By default, useSnapshot works with "sync=false".

const { count } = useValtio(state);
// That 👆 is equivalent to this 👇.
const { count } = useSnapshot(state, { sync: true });

Examples

The examples folder contains working examples. You can run one of them with

PORT=8080 pnpm run examples:01_counter

and open http://localhost:8080 in your web browser.

You can also try them directly: 01 02