Dan Mazzini
Dan Mazzini

Reputation: 1001

React/Flux efficiency: how to prevent an action from triggering multiple renders of a component?

I'm still studying the Flux architecture, and noticed that:

So, if ControllerView depends on data of two Stores, and those two Stores are both changed by one Action, the ContollerView - with all its components - will be rendered (to the virtual DOM) twice, the first time with incomplete data.

Is there any recognized pattern to avoid this? I can think of some simple solutions, but I wouldn't like to reinvent the wheel.

Upvotes: 1

Views: 973

Answers (3)

Dan Mazzini
Dan Mazzini

Reputation: 1001

I'll add this for future reference: I didn't find any good solution to this problem with vanilla Flux, and in the end switched to Redux, which has all the advantages of Flux and doesn't suffer from this disadvantage.

Upvotes: 0

wintvelt
wintvelt

Reputation: 14101

Best practice in flux pattern is to limit number of stateful components, and try only to have top component listen to stores, and send down all relevant info in props.

With multiple stores, one solution to minimize multiple renders after a single change:

  • create a StatStore that stores nothing, but listens to all relevant Actions, and waits for all other relevant stores.
  • this StatStore has getter functions, that collect (and possibly calculates stats) from other stores
  • your top component only listens to StatStore change emissions
  • top component then gets data from StatStore.

That way, a single change only results in one re-render.

Upvotes: 0

eddyjs
eddyjs

Reputation: 1280

In general, you should just allow it to render more than once. However, the if the action always triggers actions in both stores you can use the "waitFor()" method of the dispatcher to let one store update first, then only emit a change when the second store gets updated.

This is only useful if the action will always affect both stores, however.

Upvotes: 1

Related Questions