DEV Community

Cover image for How redux and context helps managing global state
Sriram
Sriram

Posted on

How redux and context helps managing global state

Why we need redux and react context to manage global states ?
Answer: To avoid anti-pattern pitfall of singleton

What is singleton?
Singleton are classes instantiated once and used globally.

For example:

let click = 0;

class catchClick {
  getInstance() {
    return this;
  }

  incrementClick() {
    return ++click;
  }

  decrementClick() {
    return --click;
  }
}

const click1 = new catchClick();
const click2 = new catchClick();
Enter fullscreen mode Exit fullscreen mode

Both weren't the same because of different reference points !

***Solution: Freeze the object *

Introducing Object.freeze()

const singletonClick = Object.freeze(new catchClick());

This freezes the object and creates a single copy across all.

But, what if I am using catchClick in multiple places ? It will cause "hidden dependency".

Basically, singleton pattern is of mutable state and can cause unknown behavior. Think about you are sending money from you account and also receiving money at the exact same split of millisecond and directly you are modifying the bank balance. Creates confusion right ?

So how redux and context is different ?
It may look like singleton (IMO) but also with read-only option which covers the mutable-state pitfall and in redux only reducer can update the state via action.

End-note: In order to avoid direct global state modification, we are using the readonly context and redux and they are amazing

Top comments (2)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
konfydev profile image
Sriram

Thanks Abhay ! Glad its useful