Are react recoil state objects silently immutable?

Viewed 453

Am using react recoil for my state management and have a moderately nested object serving as state for this particular component.

When trying to update the state with setState (the Recoil version, I'm suspecting vanilla React useState would behave similar), I grab the old version of the object, and try mutating it a bit before returning the updated state. But reassigning values on this object fails completely silently, I see no warnings, but assigning a new value has no effect. Example:

import { useRecoilState} from "recoil";

...

const [state, setState] = useRecoilState(sampleState);

const someCallback = () => {
        setState((oldState) => {
            const newState = { ...oldState };
            console.log(newState.dog.paw); // false
            newState.dog.paw = true

            //stopping the debugger here and trying to reassign in the devtools has equally no effect

            console.log(newState.dog.paw); // false
            return newState ;
        });
    };

when reassigning during a paused debugger session in chrome dev tools this is happening:

newState.dog.paw = true
true
newState.dog.paw
false

I am aware that React's documentation says that mutating the state object directly is not advisable but from that to explaining what is happening above is a gap I don't know how to fill.

I actually also know how to work around the problem, the solution is to spread reassign the parent object like so:

newState.dog = {...newState.dog, paw:true}

Having said all that, I'd be grateful for some deeper insight about what is happening up there and why is this phenomenon behaving so weirdly in the interpreter/devtools -> the reassignment seems to go through but it doesn't have any effects.

0 Answers
Related