DEV Community

Discussion on: Can React state management get any simpler than this?

Collapse
 
arnelenero profile image
Arnel Enero • Edited

You can treat an entity just like a variable. Just declare as many entities as you want. Don't think of an entity as a class that you need to "instantiate".

For example:

export const counterA = entity(0)
export const counterB = entity(0)
export const counterC = entity(0)
// and so on...
Enter fullscreen mode Exit fullscreen mode

And if you want to avoid declaring many actions that all look the same, you can do something like this:

const newCounter = () => {
  const counter = entity(0)
  const increment = by => { counter.set(value => value + by) }
  const reset = () => counter.set(0)

  return { counter, increment, reset }
}

const counterA = newCounter()
const counterB = newCounter()
const counterC = newCounter()
Enter fullscreen mode Exit fullscreen mode

This library is flexible. You can do it however you prefer.

Collapse
 
skyjur profile image
Ski • Edited

Don't think of an entity as a class that you need to "instantiate".

It's a very useful thought though - as every variable needs to instantiated with initial state. If it's class or not doesn't matter at all.

What I see here in your examples is completely no different of just using useState(). Thus I completely miss the point that you're trying to achieve.

const useCounterStore = () => {
  const [counter, setCounter]= useState()
  return { 
      counter,
      increment(by) {
         setCounter(counter+by)
      },
      reset() {
         setCounter(0)
      }
  }
}

function SomeComponent() {
   const counterA = useCounterStore()
   const counterB = useCounterStore()
   const counterC = useCounterStore()
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
arnelenero profile image
Arnel Enero

Your example would not be "shared state", is it?