Hello, I’ve invented something I’m calling the shared state model pattern for React applications.

I’ve got this default App that Expo very kindly gave me, which I’ve been building on and building on with no restraint. It has to keep track of the player, the monsters, the dungeon, the rooms in the dungeon, the room the player is in the dungeon, and at least two other things.

It also needs a bunch of callbacks that are used for child components to update that state.1 All this adds up to a lot of code hanging around the App.

Here’s a simple version of the problem:

See the Pen Shared State Model: The Problem by shane (@technicallyshane) on CodePen.

One of the things we can do is move the actions you might do to a Player into their own object.

We can start throwing in all sorts of bits about the Player, like their health and whatnot.

See the Pen Shared State Model: The Model by shane (@technicallyshane) on CodePen.

The problem now is that it’s very likely that the two will fall out of sync. Someone might call this.player.heal reasonably assuming that the view would also update. But it won’t.2

But what happens if we pass in the ability to update the state from the App?3

See the Pen Shared State Model: The Solution??? by shane (@technicallyshane) on CodePen.

Here, we begin treating the Player like a model which auto-updates to its datastore. The React state gets updated regardless of who is calling player.heal.

Of course, if you want React to realise it needs to re-render, components should always be passed the this.state based value.

App.js is very small now!

I don’t know how well this will scale, but so far it’s been fine!4

  1. Hold on, Shane. It sounds like you probably just need Redux. It’s specifically designed so you don’t need to pass – 5 

  2. So you’re going to add Redux into that object, right? At least look at the documentation. Shane??? 

  3. What? Oh, no. 

  4. I really couldn’t tell you why I did this, rather than just learning how to implement Redux. 

  5. Ssshh.