DEV Community

Enzo
Enzo

Posted on • Edited on

Mutable or immutable global state pattern in React with hooks?

I want to create a global state pattern for my next app. But I don't know if I should go for the mutable approach or the immutable one. Let me show examples illustrating my two options with pseudo-react.

Immutable

let globalState = { name: 'Enzo' }
function setGlobalName(name) {
    globalState = { ...globalState, name }
    notifySubscriber1(name)
    notifySubscriber2(name)
    // ... and so on
}

function Component() {
    const [state, setState] = useState(getGlobalState())

    function notifySubscriber1(name) {
        setState({ ...state, name })
    }

    return <Text onClick={setGlobalName('John')}>{state.name}</Text>
}
Enter fullscreen mode Exit fullscreen mode

Mutable

const globalState = { name: 'Enzo' }
function setGlobalName(name) {
    globalState.name = name
    notifySubscriber1()
    notifySubscriber2()
    // ... and so on
}

function Component() {
    const state = getGlobalState()
    const [n, forceUpdate] = useState(0)

    function notifySubscriber1() {
        forceUpdate(n + 1)
    }

    return <Text onClick={setGlobalName('John')}>{state.name}</Text>
}
Enter fullscreen mode Exit fullscreen mode

The mutable version could look dirty but let's assume that I'm going to wrap everything into a fancy API. The idea of forceUpdate comes from the MobX pattern that I once studied at that time. The pattern is pretty much the same with the difference that MobX uses Proxies to notify the component to forceUpdate.
https://github.com/mobxjs/mobx-react/issues/55#issuecomment-219536973

The thing is that I don't know what approach to take. Clearly, the mutable is much better in terms of performance because the immutable one makes a copy of the state every time we make a mutation, and this would be a problem if the store/state is a huge object.

But on the other hand, I don't know how problematic it would be the mutable way.

We can compare more or less both patterns with MobX and Redux. I know is a difficult topic because both have pros and cons. But I'm here to hear all the opinions that help me decide.

Top comments (0)