pmndrs / valtio

💊 Valtio makes proxy-state simple for React and Vanilla
http://valtio.pmnd.rs
MIT License
8.7k stars 244 forks source link

replace object not trigger render #758

Closed lake2 closed 1 year ago

lake2 commented 1 year ago

Summary

const it = proxy({
    obj: { a: 1 },
});

setTimeout(() => {
    it.obj = { a: 2 };
}, 1000);

const A: React.FC = React.memo(function A(props) {
    const snap = useSnapshot(it.obj);
    console.log('===========update', snap); // only render once

    return (
        null
    );
});

Link to reproduction

Check List

Please do not ask questions in issues.

Please include a minimal reproduction.

dai-shi commented 1 year ago
const snap = useSnapshot(it.obj);
// that ☝️ means like this 👇 
const objThatNeverChanges = it.obj;
const snap = useSnapshot(objThatNeverChanges);

So, it's how JS works. The canonical fix is to subscribe to obj itself.

const { obj: snap } = useSnapshot(it);
lake2 commented 1 year ago
const snap = useSnapshot(it.obj);
// that ☝️ means like this 👇 
const objThatNeverChanges = it.obj;
const snap = useSnapshot(objThatNeverChanges);

So, it's how JS works. The canonical fix is to subscribe to obj itself.

const { obj: snap } = useSnapshot(it);

Can I do something like replace the value to fix this? Maybe I can make a PR to implement this replacement function and include it in valtio if this is reasonable;

const it = proxy({
    obj: { a: 1 },
});

// just a simple implementation, it may be not work in some situation
const replace = (it, key, value) => {
    Object.keys(value).forEach(item => {
        it[key][item] = value[item];
    });
};

setTimeout(() => {
    replace(it, 'obj', { a: 2 });
}, 1000);

const A: React.FC = React.memo(function A(props) {
    const snap = useSnapshot(it.obj);
    console.log('===========update', snap); // only render once

    return null;
});
dai-shi commented 1 year ago

It's a reasonable practice but you don't need to make a PR for that. There are many other libraries that do similar things. Feel free to submit a PR to improve docs.