Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created December 4, 2015 10:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryanflorence/887a33c5ab3c283247fe to your computer and use it in GitHub Desktop.
Save ryanflorence/887a33c5ab3c283247fe to your computer and use it in GitHub Desktop.

For those of you asking about my "redux mental breakthrough":

I've struggled with how to keep the state of multiple instances of the same component class in redux. I kept thinking that I had an "unkown number" of instances and would need to somehow carve out a piece of state when the new instance was mounted.

I don't know why I was thinking this way. Thinking is hard, isn't it? (I'm in the UK and they often say "isn't it?" after asserting something and I love it, anyway....)

I was looking at my app that used redux where I bailed and just used component state to manage the number of instances of a <LocationForm/>. I'd click the button, increment a counter in state, and then render as many LocationForms as what the counter told me to.

Multiple instances of components don't just materialize inside of render by magic. I realized that there are only two ways to end up rendering more than one instance of a component: 1) you either make it a part of your program (hard-coded) or 2) you have some piece of state somewhere that tells you how many to create (and probably some user-interaction to tell you to do so).

  1. For whatever reason, it wasn't clear to me when I would know to "carve out a new piece of state" in redux for these component instances. When I realized I was already doing it with setState it became clear that the time to create a new bit of state in a reducer is in an action: like maybe ADD_ADDITIONAL_LOCATION is the action that increments the counter, and now I've got a new piece of state for a new LocationForm before I render one.

  2. The other time you have multiple instances is because you hard-coded them. Well, if you hard-coded them, then the time to carve out more state for each instance is also hard-coded.

That's it. Probably not very insightful to some of you, except maybe some insight into the dumb things developers you think have a clue can get tripped up on.

@insin
Copy link

insin commented Dec 4, 2015

It's a relief when you realise a concept you already understand well in a different context carries over, so it is.

That's how we "isn't it?" in Norn Iron :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment