Valtio State Proxy: Get "Argument of type 'number' is not assignable to parameter of type 'object'." with `useSnapshot`

125 Views Asked by At

Let's say my state is :

import { proxy } from 'valtio';
const initState = {
   firstName: 'name1',
   lastName: 'lname2' 
}
const state = proxy(initialState)

Now in the React component, when I tried to use the snapshot of only the firstName property on the state:

import React from 'react';
import { useSnapshot } from 'valtio';

export function MyComponent() {
    const fName = useSnapshot(state.firstName);
    return (
        <span>
            {fName}
        </span>
    );
}

I see this error: Argument of type 'string' is not assignable to parameter of type 'object'.ts(2345)

How do I fix this?

I know this works:

const { firstName } = useSnapshot(state);

But does this have any performance impact & does it really only subscribe the firstName or it subscribes to the whole store?

1

There are 1 best solutions below

0
Ben Carp On

useSnapshot expects the proxy object returned from proxy. It will then wrap the object it in a "listener" proxy, and will only subscribe the component to the values you are accessing.

function MyComponent() {
    const state = useSnapshot(state);
    return (
        <span>
            {state.firstName}
        </span>
    );
}

The snippet above will only rerender when firstName cha