classes as state manager React

You don't need Redux or any management system in React. You know this, right? Right?

But seriously people usually when they don't use state manager, they just use useState and context. And it can be sufficient.

But not always. Sometimes you need global state management, but Redux and different state managers are just inconvenient

They force immutability (you can mitigate it with libraries like immer, but still).

They often force you to use some kind of actions

What's your options? If there was a way that would allow to use plain JS objects and classes for state management.

Wait? Do I mean Mobx? Well, conceptually, yes. But the truth is you don't need ANY library for this. Mobx just wires JS objects to updates. But the thing is you can do this your self. Just write normal JS classes and put reactivity into them.

You can know think that's reinventing the wheel, but I will say it's super simple:


class Entity {
   subscribers = [];
   state = {};
   subscribe(f) { this.subscribers.push(f)}
   unsubscribe(f) { this.subscribers = this.subscribers.filter(s => s != f)}
   update(f) {
      f(this.state);
      this.subscribers.forEach(s => s(this.state));
   };
}
//.....
function Foo({ entity }) {
	// in useEffect entity would be subscribed/unsubscribed

	const handleClick = () => {
	  entity.update(state => {
    	 state.counter++;
	  })
	}
}

this way:

You throw away needless abstractions from libraries and make something yourself which is more minimal and suited to your needs

(though alternative would be to use library which is pretty minimalistic. Libraries are not bad. I think the problem is that libraries are often too opinionated and force to use more tangled style).

You don't need immutability. You just mutate your state and it will update your components. Just like that.

You throw dependency of external library, so less problems with bundle size, upgrading to newer library versions or something.

Comments

Popular posts from this blog

First steps with Plotly.js

How to be a modern front-end dev?